Hi All,
I am new to ionic 3 and I am facing the problem of using an httpclient response given by remote server.
This is my code:
getCategoryDetail(id){
this.http.get(this.baseUrl+‘categories/’+id)
.map(response => {
this.data = response;
console.log(this.data);
})
.subscribe();
console.log(this.data);
return this.data;
}
In upper console.log function I am getting the correct data but in lower console.log function , I am getting just an empty array. Please help me
http.get() is asynchronous, so you have to wait for its execution to be able to get the response.
I would suggest:
async getCategoryDetail(id) {
return await this.http.get(this.baseUrl+'categories/'+id).toPromise();
}
Your getCategoryDetail() method will then return a Promise instead of the data, so the caller will also have to wait for the promise to be resolved.
1 Like
It is because , HTTP GET request is in async , and before getting response from api, you are accessing
this.data, which is definatety not set yet.
Try this flow
// Will return Observable
getCategoryDetail(id) {
return this.http.get(this.baseUrl+‘categories/’+id);
}
// Subscribe that Observable then
this.getCategoryDetail(id).subscribe((response) => {
this.data = response;
})
2 Likes
Thanks for your immediate response. That work good