I'm trying to build a sequence of RXJS commands in a guard, in order to achieve this result in a simple library (as in books) application :
- Check in the Store
- If the state is not loaded, trigger an action
- Once it's loaded, filter the data to find one specific item
- If you find it, allow access to page, if not, send to 404
I've been struggling for a while and looking online does not give an answer according to version 6 of Angular, or standards... What I've succeeded into doing what to create much of it if the store is loaded before hitting the guard, but if it needs to fetch the data, it loops indefinitely.
canActivate(route: ActivatedRouteSnapshot): Observable<boolean> {
return this.store.pipe(
select(state => state.books),
tap(state => {
if (!state.loaded) {
this.store.dispatch(new BooksActions.Load());
}
}),
filter(state => state.loaded),
take(1),
map(state => state.list.find(book => book.id === route.params['id'])),
map((book) => {
if(!!book) return true;
this.router.navigate(['/404']);
return false;
})
);
}
Thanks a lot!