Problem with http request in ionic 2

Inside my provider, I have this code:

  getData() {
    this.http.get('https://newsapi.org/v1/articles?source=cnbc&sortBy=top&apiKey=bb4b99213d39444599aba09a983395f2').map(res => res.json()).subscribe(data => {
      this.news = data.data.children;
      return this.news;
    });
  }

but its showing data to be undefined, please help.
Thanks.

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: