3

I have a component where I get a route parameter:

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;
    })

  }

}

Then on the template I have:

<product-list [category]="category"></product-list>

And ProductList component is:

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);

  }

}

The problem is when route parameter category changes the Products rendered by ProductList component are not updated.

How can I solve this?

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481

1 Answers1

2

you need to implement ngOnChanges in ProductListComponent

like below

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

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

    // reload your data here
  }
}
Reza
  • 18,865
  • 13
  • 88
  • 163
  • I believe params does not need to be unsubscribed (https://angular.io/guide/router#!%23route-parameters) as described in Angular Docs: "When subscribing to an observable in a component, you almost always arrange to unsubscribe when the component is destroyed.There are a few exceptional observables where this is not necessary. The ActivatedRoute observables are among the exceptions. The ActivatedRoute and its observables are insulated from the Router itself. The Router destroys a routed component when it is no longer needed and the injected ActivatedRoute dies with it." Am I wrong? – Miguel Moura Jul 09 '19 at 17:30
  • @MiguelMoura seems you are right ;) btw I always unsubscribe by creating a variable `unsubscribeAll : Subject = new Subject()` and pipe all my subscription with `takeUntil(this.unsubscribeAll)` and in `ngOnDestroy` `unsubsribeAll.next()` and `unsubscribeAll.complete()` – Reza Jul 09 '19 at 17:46