I am checking out the ngrx example app and trying to figure out a good way to initialize state on the find page (http://localhost:4200/#/books/find).
It seemed like I should be able to add this to the AppComponent
ngOnInit() {
this.store.dispatch(new book.Search('Michael Jordan'));
}
but that is not populating the store in the FindBookPageComponent
it seems like it happens too early in the chain.
Wondering if someone can explain this and offer a better way.
Note:
Adding the ngOnInit to the FindBookPageComponent
works but it would get called every time the person navigates back. I would like this to be more of a initial state if that makes sense.
Thanks!
Its better to put it in router guards => canActivate()
check for data exists or not in store; else dispatch the load data
canActivate(): Observable<boolean> {
return this.checkStore().pipe(
switchMap(() => of(true)),
catchError((error) => of(false))
);
}
checkStore(): Observable<boolean> {
return this.store.select(fromStore.getDataLoaded).pipe(
tap(loaded => {
if (!loaded) {
this.store.dispatch(new fromStore.LoadDataCollection());
}
}),
filter(loaded => loaded),
take(1)
);
}