I have a guard, where I want to ensure the data is pre-loaded before the page visually loads. I've been following Todd Motto's strategy, for pre-loading data that only requires one dispatch.
The issue is, my scenario requires multiple dispatches, where some are dependent on others.
I need to dispatch to load object A
, then I need to use some data on object A
to load object B
.
For the sake of this minimal example, assume my state has loading
(boolean), and things[]
(loaded entities). When I do a Get
action, loading
is flipped to true. loading
gets flipped to false on an unseen success action.
canActivate(route: ActivatedRouteSnapshot): Observable<boolean> {
// fetches the first `thing` with the route's id
this.store.dispatch(new actions.Get(route.params.id));
return this.store
.select(selectState)
.filter(state => !!!state.loading)
.do(state => {
// the first `thing` is loaded
// now use it to load another `thing`
this.store.dispatch(new actions.Get(state.things[0].something));
})
.take(1)
.switchMap(() => this.store.select(selectState))
// in the filter, state.loading is false, even though
// we just fired a dispatch to say it's loading.
// ...because this is checked before the
// dispatch can flip the boolean
.filter(state => !!!state.loading)
.take(1)
.switchMap(() => Observable.of(true))
.catch(() => Observable.of(false));
}
While everything works fine for the first "wait for this to load", the subsequent dispatches don't flip my loading
state variable to true before the next "wait for this to load" check.
Any help, or maybe a better pattern, is greatly appreciated.