Angular 2 rxjs nested observables

I want to create a function that returns an Observable<any> , but before returning another asynchronous task, it must complete (a Observable<string> ) in order to pass the value 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); }) } } 

Therefore, instead of passing the authToken parameter to the GetData function, I want to execute the GetAuthToken function inside the GetData function, wait for it to complete, and then return the http observable.

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

+6
source share
2 answers

Try using concatMap() :

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

It is also possible with flatMap

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

Source: https://habr.com/ru/post/1012106/


All Articles