如何拒绝路由,直到数据存储在ngrx中并解决?

时间:2019-01-20 12:50:10

标签: ngrx angular7 ngrx-store angular-resolver

在商店中没有数据之前,我想拒绝用户进行路由。 我尝试使用解析器,但它仍然可以到达路线,并且由于在状态效果中使用此数据而导致错误。 我在网上搜索过,但没有看到将用户保留在解析器中的示例,直到数据解析完毕 我如何“保留”用户,直到我的商店中拥有必要的数据?

enter image description here

1 个答案:

答案 0 :(得分:0)

使用canActivatecanLoad卫队。托德·莫托(Todd Motto)撰写了有关如何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));
  }