Using route resolver I am trying to get a data from store as follows
export class GetActiveCustomerService implements Resolve<any> {
constructor(private store: Store<AppState>) {}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): any {
return this.store.select('customer').pipe(
first(),
map((data) => {
return data.customer;
})
);
}
}
The previous attempt always returns null
What is the correct way to resolve the data stored in the store?
update 0
This modification returns the expected result. But when refreshing the browser the data is null. I understand it is because of take(1)
. If this is the route to achieve what I mentioned, how can I make the data survive refreshing?
export class GetActiveCustomerService implements Resolve<any> {
constructor(private store: Store<AppState>) {}
private getActiveCustomer(): Observable<any> {
return this.store.select('customers').pipe(take(1));
}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): any {
return this.getActiveCustomer();
}
}
update 1
I found this answer
https://stackoverflow.com/a/58711499/615274 from someone who was facing a problem similar to mine. And the accepted solution uses take(1)
or first()
. But in my local when refreshing the obtained data it becomes null
. What is the proper way to handle this scenario?
CodePudding user response:
Ngrx does not keep/save your data after reload. Use local storage or cookies to save your data before refreshing the page.
CodePudding user response:
I'm not sure of what you're trying to achieve.
If the logic is to be able to refresh a page with a parameter (selectedProductId) in it and then display in a component (ProductDetailComponent) the corresponding data, taking into account the parameter, there's two solution for that using ngrx:
- Either you have somewhere in your store a selectedProductId that is updated using a Guard. Thus each time the page is refreshed the Guard set up the selectedProductId and you have a specific selector that will use the selectedProductId to get the proper data.
- Or use ngrx/router that will do most of the work for you and provide you with selectors for each parameter in your url.
Obviously in both case you have to ensure that:
- You call the back to get the data because everything is removed from the store when you refresh the page.
- You have a boolean in your store "isLoaded" that is set to false in the initial state and set to true when you receive the data, and you display a spinner or whatever you want while waiting for the data.