When it comes to ensuring the protected view of an entity, I utilize a RouteGuard
to pre-load the necessary data for the desired view into the ngrx store. However, as the corresponding data from the backend can be subject to change over time, it is crucial that each time the route is activated, the old state of the store gets updated with the latest data retrieved from the backend. This update should only occur once the new data has been successfully loaded into the store and made available. It's important to consider scenarios where the entity may have been deleted on the backend in the meantime.
To illustrate this concept further, here is a minimal example: Stackblitz Example
In the current setup, the action GetEntity()
is invoked every time the route is accessed, triggering a call to retrieve data from the backend. Despite this, the route still becomes active based on the previous state of the store, which is not the intended behavior. To address this issue, there needs to be a way to invalidate or clear the old state to prevent the route from being activated mistakenly.
Here is the logic within the canActivate
function of the RouteGuard
:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.store.pipe(select(selectEntityMap)).pipe(
map(taskMap => Object.keys(taskMap).length > 0),
tap(loaded => {
this.store.dispatch(GetEntity()); // trigger backend loading
}),
filter(loaded => !!loaded), // wait until the entities have been loaded.
take(1),
);
}
This raises two key questions:
- How can I modify the RouteGuard to refresh the data from the backend each time it's activated, ensuring that the route is only enabled with the most recent data?
- Is the RouteGuard the appropriate place to handle the logic of fetching data from the backend repeatedly, or are additional adjustments to the state or effects required?