gunwin
gunwin

Reputation: 4832

Angular 2 rxjs nested Observables

I wish to create a function that returns an Observable<any> but before returning another asyncronous task must complete (an Observable<string>), in order for a value to be passed to the returned Observable.

 @Injectable()
 export class MyComponent
 {

      GetAuthToken = function() : Observable<string>
      {
           return this._storageService.GetAsString('authToken');
      }

      GetData = function(authToken) : Observable<any>
      {

           let headers = new Headers();
           headers.append('authToken', authToken);
           var getUsers = this._http.get('/api/endpoint', { headers: headers })
                 .map((resonse: Response) => resonse.json()));

           return getUsers;        
      }


      DoIt = function() : Observable<any>
      {
          this.GetAuthToken ().Subsribe(t=> {
              return GetData(t); 
          })
      }          


 }

So instead of passing the authToken parameter into the GetData function, I wish to execute the GetAuthToken function within the GetData function, wait for its completion, and then still return the http observable.

Executing the DoIt function would return the subscriber, not the GetData Observable

Upvotes: 6

Views: 4220

Answers (2)

gunwin
gunwin

Reputation: 4832

This is also possible using flatMap

DoIt() : Observable<any>
{
    return this.GetAuthToken()
        .flatMap(token => this.GetData(token)); 
}   

Upvotes: 0

martin
martin

Reputation: 96891

Try using concatMap():

DoIt() : Observable<any>
{
    return this.GetAuthToken()
        .concatMap(token => this.GetData(token)); 
}   

Upvotes: 10

Related Questions