Reputation: 1104
I have created a wrapper for angular 2 http service which has a post method as below. It returns an observable.
post(url:string, data:any, headers:any, animation:boolean):any{
let thisObject = this;
if(animation!=false) {
thisObject.emitCallStateChange(true);
}
return this._http.post(url,data,headers).finally(function(){
thisObject.emitCallStateChange(false);
});
}
And i consume it like so:
return this._http_service.post(ConfigService.BASE_URL+'api/auth/forgotpass',email,{
headers:headers
},true);
What i want to do is to perform a GET for csrf validation request and append csrf token before returning this observable in the post
method. So, i tried to wrap one observable within another like below:
this._http.get("api/getCsrf").subscribe(csrf=>{
let body = csrf.json();
data += "&_csrf="+body._csrf;
console.log(data);
return this._http.post(url, data, headers).finally(function () {
thisObject.emitCallStateChange(false);
});
});
But it does not work for the obvious reason that it needs to return an observable
. I need a way to return the final observable with the post
request once the request for csrf completes. Is there a way i can chain observables and only return one of them?
Upvotes: 1
Views: 1285
Reputation: 202286
You could leverage the flatMap
operator for this:
this._http.get("api/getCsrf").flatMap(csrf=>{
let body = csrf.json();
data += "&_csrf="+body._csrf;
console.log(data);
return this._http.post(url, data, headers).finally(() => {
thisObject.emitCallStateChange(false);
});
});
});
Upvotes: 2