Search code examples
angulartypescriptrxjs6rxjs-pipeable-operatorsrxjs-observables

Angular route guard/resolver - Type 'Observable<boolean | object[]>' is not assignable to type 'Observable<boolean>'


I am using a route guard (or resolver, I have tried to use either but got the same error) where I want to get Observable as a return value:

canActivate(): Observable<boolean> {
    return this.store.pipe(
      select(fromUserProfileState.getUserProfiles),
      tap((loaded: UserProfile[]) => {
        if (!loaded || loaded.length == 0) {
          this.store.dispatch(new fromUserProfileActions.LoadUPs());
        } else {
          return of(true);
        }
      }),
      filter((loaded: UserProfile[]) => loaded.length > 0),
      first()
    );
  }

However, this doesn't return Observable, it returns Observable which is not acceptable. How can I tweak the rxjs (v 6.5.5) operators to return Observable only?

enter image description here


Solution

  • Try this:

    canActivate(): Observable<boolean> {
      return this.store.pipe(
        select(fromUserProfileState.getUserProfiles),
        // Convert the information from UserProfiles to a boolean
        // Thils will also be used to authorize the navigation
        map((loaded: UserProfile[]) => !!(loaded && loaded.length)),
        // dispatch an action is no user profile has been loaded
        tap((isLoaded: Boolean) => {
          if (!isLoaded) {
            this.store.dispatch(new fromUserProfileActions.LoadUPs());
          }
        }),
        // complete the observable
        take(1)
      );
    }