【问题标题】:How to use route parameter as argument for a service method?如何使用路由参数作为服务方法的参数?
【发布时间】:2018-06-18 12:09:38
【问题描述】:

我正在尝试将产品详细信息获取到单个产品的路线。 目前 我有带有 id 参数的单个产品的路线,它工作正常

{ path: 'single-product/:id', component: SingleProductComponent }

在组件打字稿中:

 id: string;
 private mainSub: any;
 public ngOnInit(): void {
  this.mainSub = this.route.params.subscribe(params => {
     this.id = params['id'];
  }
   this.productsService
    .all()
    .map(res => res.filter(item => item.id === this.id))
    .subscribe(resp => console.log(resp));      
 });
 }

在控制台中,我得到了正确的产品,但是如何将数据获取到视图中?

【问题讨论】:

    标签: angular typescript rxjs angular-routing angular-services


    【解决方案1】:

    第一件事:

    让我们将过滤器逻辑封装在服务类中:

    export interface Product {
     // define the properties for your product
    }
    
    @Inject()
    export class ProductService {
     ....
     // constructor injetction and other methods
     ....
    
     all(): Observable<Product[]>{
       // implementation
     }
    
     getById(id:string): Observable<Product> {
       // or maybe could your backend offer an endpoint that does this for you?
       // something like `root/api/products/:id`;
       return this.all().map(products => products.find(product => product.id === id));
     }
    }
    

    现在我们可以回到组件:

    import 'rxjs/add/operator/switchMap'; // Maybe replace with lettable operators
    
    @Component({...})
    export class FooComponent {
     product$: Observable<Product>;
     constructor(private _route: ActivatedRoute, private _productService: ProductService){
        this.product$ = _route.paramMap
           .map(params => params.get('id')) // maps the route params. map to the id key
           .switchMap(id => _productService.getById(id));// change the main stream to the stream returned by the service
     }
    }
    

    现在在您的模板中,您可以使用一个小技巧来访问product$ 流中的最新值:

    <ng-container *ngIf="product$ | async as product">
       {{ product | json }}
       // your template goes here
    </ng-container>
    

    【讨论】:

      【解决方案2】:

      使用以下代码在您的组件中实现:

       id: string;
       product: any;
       private mainSub: any;
       public ngOnInit(): void {
        this.mainSub = this.route.params.subscribe(params => {
           // I used + sign if id is number otherwise remove it
           this.id = +params['id'];
           this.productsService
            .all()
            .map(res => res.find(item => item.id === this.id))
            .subscribe(resp => this.product = resp);      
          });
        }
       }
      

      现在在您的 html 模板中使用您的数据,如下所示(虚拟 html):

      <table>
        <tr>
          <td>Product Name</td>
          <td>{{product.productName}}</td>
        </tr>
      </table>
      

      【讨论】:

      • 我已经这样做了,但出现错误“无法读取未定义的属性'名称'”
      • 你能把你的回复贴在这里吗?
      • console.log 响应是数组
      • 实际上发现工作了,但为什么控制台在获取数据时出错
      • 你能在这里评论登录浏览器控制台的错误吗?代码很好,可能在服务中有一些问题。
      猜你喜欢
      • 1970-01-01
      • 2020-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-19
      • 1970-01-01
      • 2021-11-08
      相关资源
      最近更新 更多