rxjs switchMap not working in Angular Guard?
Asked Answered
D

1

5
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;

Displease answered 13/9, 2019 at 14:57 Comment(2)
please write the errorReplay
@KhashayarPakkhesal there's no error, the route doesn't activate. I've added a catchError operator just to be safe and there's no error either. I've checked to see if that code runs inside the switchMap and it does, if I log something on the console there it will show up when I try to activate the route.Displease
K
7

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)
);
Kiri answered 13/9, 2019 at 15:9 Comment(2)
Never completes or maybe never emits. Both would stop it from loading.Longplaying
This works -- I did not know the guard needs a completing observable. Thanks a bunch!Displease

© 2022 - 2024 — McMap. All rights reserved.