Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 369
gunwin Avatar asked Nov 07 '16 15:11

gunwin


1 Answers

Try using concatMap():

DoIt() : Observable<any>
{
    return this.GetAuthToken()
        .concatMap(token => this.GetData(token)); 
}   
like image 66
martin Avatar answered Oct 22 '22 23:10

martin