路由参数更改时更新列表

Update list when route parameter changes

我有一个获取路由参数的组件:

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 组件呈现的产品未更新。

我该如何解决这个问题?

您需要在 ProductListComponent

中实施 ngOnChanges

喜欢下面

ngOnChanges(changes: Record<keyof ProductListComponent, SimpleChange>) {

  if (changes.category && changes.category.currentValue) {

    // reload your data here
  }
}