I have a provider class having a request function. It works fine:
sendRequest(requestBody:any,URL:string){
let headers = new Headers();
headers.append("Accept", 'application/json');
headers.append('Content-Type', 'application/json' );
let options = new RequestOptions({ headers: headers });
let body=requestBody;
body.key=this.key;
this.http.post(this.url+URL, body, options)
.subscribe(data => {
let json=JSON.parse(data['_body']);
let toast=this.toast.create({
message:json.response,
duration:3000,
position:'top'
});
toast.present();
return json;
}, error => {
console.log(error);// Error getting the data
});
}
I want to call this method and want json response in another class. I tried calling in promise but didn't worked out. Any help would be highly appreciated.
Edit: I want to perform toast as well as I tried returning this.http.post... it is returning a subscribe object. How can I fetch json data from that?
**Edit # 2 ** I successfully returned the data using map on definition and subscribe on call side.
return this.http.post(this.url+URL, body, options)
.map((data) => {
let json=JSON.parse(data['_body']);
let toast=this.toast.create({
message:json.response,
duration:3000,
position:'top'
});
toast.present();
return json;
}
and called using
this.request.sendRequest(requestBody,'api/login').subscribe((data)=>{
console.log(data);
});
Toast works too.
Solved
return this.http.post ...then you can call it from another method