Angular、store-select 与 http get

Angular, store-select with http get

我想守护一条路线并执行以下操作:

这是我目前得到的:

@Injectable({providedIn: 'root'})
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router, private store: Store<AppState>) {
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return this.store.select(selectUser).pipe(
      take(1),
      map(user => {
        if (!!user) {
          return true;
        }

        return this.authService.getUser$()
          .pipe(
            map(user => {
              this.store.dispatch(addUser({user: user}));
              return true;
            })
          )
      })
    );

  }
}

错误:

Type 'Observable<true | Observable<boolean>>' is not assignable to type 'boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree>'.

问题是 return this.authService... return 是一个 Observable,它导致 可观察<可观察>.

如何解开这个心结?

        if (!!user) {
          return true; // Returns a boolean - OK
        }

        return this.authService.getUser$()
          .pipe(
            map(user => {
              this.store.dispatch(addUser({user: user}));
              return true; // Returns an observable of a boolean - Not OK
            })
          )

替换为 switchMap :

    return this.store.select(selectUser).pipe(
      first(),
      switchMap(user => {
        if (!!user) {
          return of(true);
        }

        return this.authService.getUser$()
          .pipe(
            map(user => {
              this.store.dispatch(addUser({user: user}));
              return true;
            })
          )
      })
    );