我有一个可以获取路由参数的组件:
export class CatalogComponent implements OnInit {
category: number;
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.route.paramMap.subscribe(parameters => {
this.category = parameters.has('category') ? +parameters.get('category') : undefined;
})
}
}
然后在我拥有的模板上:
<product-list [category]="category"></product-list>
ProductList组件为:
export class ProductListComponent implements OnInit {
@Input() category: number;
products$: Observable<ProductListModel[]>;
constructor(private productService: ProductService) { }
ngOnInit() {
this.products$ = this.getProducts();
}
private getProducts(): Observable<ProductListModel[]> {
return this.productService.get(this.category);
}
}
问题是路由参数category
更改时,ProductList组件提供的产品未更新。
我该如何解决?
答案 0 :(得分:2)
您需要在ngOnChanges
中实现ProductListComponent
如下所示
ngOnChanges(changes: Record<keyof ProductListComponent, SimpleChange>) {
if (changes.category && changes.category.currentValue) {
// reload your data here
}
}