Problem with http request in ionic 2

Inside my provider, I have this code:

  getData() {
    this.http.get('').map(res => res.json()).subscribe(data => { =;

but its showing data to be undefined, please help.

What do you get when you console.log(data)?

same, that data is undefined. :frowning:

Because subscribe is asynchronous. The console.log don’t wait for your data you subscribed to.

please tell me what to do? even if i try to return the value from the function, the error occurs.

Whenever you call a function that returns a future, one of two things should be true:

  • the calling function returns void
  • the calling function returns a future, and the first word of said function is return

Noticeably absent from this list is “the calling function returns the resolution (data) from the called future”, because that is impossible.

So, generally, you want to do this:

in provider:

getSomething(): Observable<Something> {
  return this._http.get(url).map(rsp => rsp.json());

in consumer:

this._provider.getSomething().subscribe(got => this.something = got);
1 Like

Thanks it worked! :slight_smile: