如何使用路由参数作为服务方法的参数?

How to use route parameter as argument for a service method?

我正在尝试获取产品详细信息到单个产品的路线。 目前 我有带有 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));      
 });
 }

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

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

 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>

要事第一:

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

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>