Search code examples
angularrxjsangular-router-guardsswitchmap

rxjs switchMap not working in Angular Guard?


return this.auth.user.pipe(
      switchMap((user: IUser) => {
        return of(true);
      })
    );

My initial code was a bit more complex with some cases depending on the user data, but for testing purposes I've used the code above in a guard's canLoad and it does not activate.

There's TS/compilation errors whatsoever.

I've tried it both with Ivy and without.

I'm using Angular 8.3;


Solution

  • You have to use a take(1), because I'm sure the auth.user is a stream and does not complete. A guard needs to have a completing Observable:

    return this.auth.user.pipe(
      take(1),
      switchMap((user: IUser) => of(!!user))
    );
    

    Perhaps you removed some code, but you can also just use map here:

    return this.auth.user.pipe(
      take(1),
      map((user: IUser) => !!user)
    );