queryParams
,然后运行
getProducts()
在那个订阅上。如下所示,在相同的组件中
getProducts
import { ActivatedRoute } from '@angular/router';
//...
@Component({
//...
})
export class SomeComponent {
constructor(
private activatedRoute: ActivatedRoute
) {
this.activatedRoute.queryParams.subscribe(params => {
this.getProducts(Number(params['category']));
});
}
//getProducts() {}
}
编辑到
获取产品
,根据评论。
cannot read "filter" of undefined
因为你正在设置
this.products
在异步承诺之后,这是正确的,但您的过滤器函数不在该异步调用中。如下所示进行调整,这将允许您将上述函数保留在构造函数中。
// Products from the API
getProducts(categoryId?: number): void {
if (categoryId) {
this.productService.getProducts()
.then(products => {
this.products = products.filter((product: Product) => product.categoryId === categoryId);
});
} else {
this.productService.getProducts()
.then(products => this.products = products);
}
}