Reputation: 4102
I'm using RXJS 6.5.4
In my typescript service I have:
isAuthenticated(): Observable<boolean> {
// request
}
currentUserPromise(): Promise<User> {
// request the User model and return via Promise.
}
My second method, I need to verify if the session is authenticated, then request the current user and transform this to another Observable to resolve if the current user is an admin.
I'm trying this, but I'm getting errors:
isAdmin(): Observable<boolean> {
this.isAuthenticated().pipe(map(authenticated => {
if (authenticated) {
return from(this.currentUserPromise().then(user => user.roles.indexOf('ADMIN') > -1)
}
return mapTo(false); // there is no authentication, so no current user and no admin!
}));
}
And this is the compile error:
Type 'Observable<Observable<boolean>>' is not assignable to type 'Observable<boolean>'.
Type 'Observable<boolean>' is not assignable to type 'boolean'.ts(2322)
Upvotes: 1
Views: 46
Reputation: 29325
if you need to subscribe to an inner observable, you need a higher order operator like switchMap
, map
is for synchronous data transforms. mapTo
is an operator and can't be used like you were using it, use of
to turn a value into an observable... also you need to return it for it to be subscribed to.
isAdmin(): Observable<boolean> {
return this.isAuthenticated().pipe(switchMap(authenticated => {
if (authenticated) {
return from(this.currentUserPromise().then(user => user.roles.indexOf('ADMIN') > -1))
}
return of(false); // there is no authentication, so no current user and no admin!
}));
}
Upvotes: 2