Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;

like image 816
SebastianG Avatar asked Sep 13 '19 14:09

SebastianG


1 Answers

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)
);
like image 51
Poul Kruijt Avatar answered Nov 10 '22 06:11

Poul Kruijt