I am trying to call a web service in ionic 2 application but getting struck in between promise and observable. This is my function which i am calling on click of a button-
getUserDetailsIfAccessTokenIsSuccess()
{
this.remedyService.userGetDetail(this.loginDetailsObj.username).subscribe(
data =>{
console.log("userGetDetail Success="+JSON.stringify(data));
},
err =>{
console.log("userGetDetail Success="+JSON.stringify(error));
},
() =>{
console.log("Get Userdetails Completed");
});
}
Now i am calling userGetDetail function in my service file.
userGetDetail(eid){
var url = '/userGetDetail';
var params = {
'EID':eid
};
console.log(JSON.stringify(params));
var headers = new Headers();
this.createAuthorizationHeader(headers);
this.storage.get('remedyAccessToken').then((value)=>{
var token = value.toString();
console.log("TOKEN IN REMEDYSERVICES="+token);
headers.append('Authorization', token);
console.log("header value inside="+JSON.stringify(headers));
})
console.log("header value outside="+JSON.stringify(headers));
let options = new RequestOptions({ headers: headers });
this.response = this.http.post(url,this.urlEncode(params),options).map(res => res.json());
console.log("Response JSON="+JSON.stringify(this.response));
return this.response;
}
Now the issue is that before Authorization is getting appended to header the flow is going to next line and web api is giving error. Is there anyway i am can synchronise in such a way that after Authorization is appended then only service call should happens. I tried putting the web api call inside then block but it makes the service calls as a promise. Any help will be appreciated.
The correct way to call an observer inside a promise and the return an observer will be like this-
return Observable.fromPromise(this.storage.get('remedyAccessToken')).then((value)=>{
var token = value.toString();
console.log("TOKEN IN REMEDYSERVICES="+token);
headers.append('Authorization', token);
console.log("header value inside="+JSON.stringify(headers));
console.log("header value outside="+JSON.stringify(headers));
let options = new RequestOptions({ headers: headers });
this.response = this.http.post(url,this.urlEncode(params),options).map(res => res.json());
console.log("Response JSON="+JSON.stringify(this.response));
return this.response.toPromise();
})