When route change the getter not recalculate which cause to wrong data

Viewed 66

I want to select from the store the productId from the route.

so I have getter function in my component:

get productId() {
 const x = this.route.snapshot.paramMap.get('productId');
 console.log({ x });
 return x;
}

product$ = this.store.pipe(select(selectProductById, { productId: this.productId }));

The problem is when I navigate to another product, the product$ doesn't change. because the getter is not recalculate. and the selectProductById not recalculate either.

What can I do to get the product$ when the route change?

1 Answers

Snapshot won’t get updated if we try to reload the current route with different route parameter.
In your case you should use subscribe instead of snapshot:

this.route.params.subscribe(params => {
    const productId = params['productId'];
    product$ = this.store.pipe(select(selectProductById, { productId: productId}));
});

More explanation: https://angular.io/guide/router#getting-route-information

Related