gunwin gunwin - 25 days ago 30
Javascript Question

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

Answer

Try using concatMap():

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