Angular / NgRx-在Guard中合并2个选择器

时间:2019-04-16 10:45:20

标签: angular rxjs ngrx

我有一个canActivate,其中我有2个状态

canActivate(): Observable<boolean> {

this.store.dispatch(new fromProjectActions.SelectProjectAction(43))

  combineLatest(
    this.store.pipe(
      select(fromProjectSelectors.getSelectedProject)
      ),
    this.store.pipe(select(fromUserSelectors.getUser))
    ).pipe(
      map(([project, user]) => {
        // Logic here
        // return true if project.creatorId === user.id
      })
    );
}

知道getUser在该状态下已经可用时,我该怎么做,但是getSelectedProject有必要在此之前分派其动作

编辑:

canActivate(): Observable<boolean> {
    this.store.dispatch(new fromProjectActions.SelectProjectAction(43));

    combineLatest(
      this.store.pipe(
        select(fromProjectSelectors.getSelectedProject)
        ),
      this.store.pipe(select(fromUserSelectors.getUser))
      ).subscribe(([project, user]) => {
        // here the first time `project` is `null`, have to wait the 
          second time
        if (project) {
          if (project.id === user.id) {
            return of(true);
          } else {
            return of(false);
          }
        }
      });
}

1 个答案:

答案 0 :(得分:1)

如果您的问题是select(fromProjectSelectors.getSelectedProject)发出null,则可以将其过滤掉:

combineLatest(
  this.store.pipe(
    select(fromProjectSelectors.getSelectedProject).pipe(
      filter(project => !!project))
    ),
  this.store.pipe(select(fromUserSelectors.getUser))
  ).subscribe( ...