I am trying to create a guard for my routes based on the payload I received in the JWT token. The problem is that I have the first method (authService.getToken()) returning an Observable of NbJWTAuthToken and then I need to query again using the token like in token.getPayload() to then retrieve the payload.
Here is what I tried without much success:
@Injectable()
export class AdminGuard implements CanActivate {
constructor(private authService: NbAuthService) { }
canActivate() {
return this.authService.getToken()
.pipe(
flatmap(token => token.getPayload()),
tap((account:Account) => account.type === AccountType.ADMIN)
);
}
}
Any ideas?
You were pretty close. Just use Rxjs 'map' operator instead of 'tap'.
@Injectable()
export class AdminGuard implements CanActivate {
constructor(private authService: NbAuthService) { }
canActivate() {
return this.authService.getToken()
.pipe(
flatmap(token => token.getPayload()),
map((account:Account) => account.type === AccountType.ADMIN)
);
}
}
Explanation
canActivate() method can accepts return type of Observable<boolean>. In your Observable you were using tap operator which returns nothing (void). Using the map operator you can return a boolean result (as you already have in the question).