What is the best way to get the changes of routing data resolver in an Angular component?
I am trying to build a component that displays data from a GraphQL Endpoint. The data is fetched using a routing data resolver, which retrieves the data before the component is loaded.
However, I want to be able to refresh the data in the component if the route parameter changes. Is there a way to fetch the updated data in the component, or do I need to use some other approach?
Currently, here's my routing configuration
{
path: 'product/:productCode',
component: ProductComponent,
resolve: {
product: ProductResolver
}
}
On the constructor of my component, I retrieve the data by doing this
constructor(route: ActivatedRoute) {
const product = route.snapshot.data.product;
}
For the resolver, it only retrieves data and it is insignificant to the question.
On the first initialisation, I have no problem retrieving the data, but when I navigated to the same component with different route parameter (productCode).
I understand the component has been initialised and the constructor only runs during initialisation. But I have tried using the ngOnInit
and ngOnChanges
lifecycle hooks, but these only seem to run when the component is first loaded, and not when the data changes.
Any suggestions or examples of how to approach this problem would be greatly appreciated.
CodePudding user response:
in provided code activatedRoute.snapshot is used, which is not updated. but you could retreive actual data from the activatedRoute itself, but it comes as observable. something like this piece of code should do well:
route.data.subscribe(({product}: {product: Product}) => {
this.product = product;
// any other code that should be executed when values changes
})