Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return observable in observable map in Angular

Tags:

angular

rxjs

I can really find no words for what I want to do. So I just show my attempt..This is what I tried:

register(): Observable<boolean> {

   return this.registerNew().pipe(
     map(userData => {
       return this.updateProfile().pipe(                   (*1)
         map(profileData => {
           return profileData ? true : false;
         }))
     }))
}

But of course I get the following error message:

Type 'Observable<false | Observable<boolean>>' is not assignable to type 'Observable<boolean>'.

I am also thinking about using await instead of return in the line which I marked with (*1).

But still I can't get it to work in a nice way.

like image 881
L. Heider Avatar asked Dec 18 '22 16:12

L. Heider


1 Answers

If you want to switch from one observable to another and use the value from the previous there is a switchMap operator which can be used like that

register(): Observable<boolean> {
  return this.registerNew().pipe(
    switchMap(userData => {
      return this.updateProfile().pipe(
        map(profileData => {
          return profileData ? true : false;
        }))
     }));
}

What causes to happen registerNew, then it passes resulting value to the switchMap returning observable (switchMap has to return an observable to work) and then the result of the inner observable (updateProfile) comes to subscriber.

like image 149
Sergey Avatar answered Jan 05 '23 00:01

Sergey