路由参数更改时更新列表

时间:2019-07-09 16:59:06

标签: angular angular7 angular7-router

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

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

我该如何解决?

1 个答案:

答案 0 :(得分:2)

您需要在ngOnChanges中实现ProductListComponent

如下所示

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

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

    // reload your data here
  }
}