Search code examples
ngrxangular7ngrx-storeangular-resolver

how to deny the route to switch until has data in store with ngrx and resolve?


i want to deny the user from getting to route until i have data in my store. i tried with resolver but it still go to the route and im getting an error because im using this data in the state effect . i searched in the web but i not see example that holds the user in resolver until the data is resolved how can i "hold" the user until i will have the necessary data in my store?

enter image description here


Solution

  • Use a canActivate or a canLoad guard. Todd Motto has an article on how to do this Preloading ngrx/store with Route Guards

    @Injectable()
    export class CoursesGuard implements CanActivate {
      constructor(private store: Store<CoursesState>) {}
    
      getFromStoreOrAPI(): Observable<any> {
        return this.store
          .select(getCoursesState)
          .do((data: any) => {
            if (!data.courses.length) {
              this.store.dispatch(new Courses.CoursesGet());
            }
          })
          .filter((data: any) => data.courses.length)
          .take(1);
      }
    
      canActivate(): Observable<boolean> {
        return this.getFromStoreOrAPI()
          .switchMap(() => of(true))
          .catch(() => of(false));
      }