How to call an API in ionic 2

We have to add a Provider which can be used to make an HTTP request to an API. In order to create a Provider run the following in the root of the Ionic project,

ionic g provider NewsService

This will create a folder as providers which contains news-service.ts file.

Now, create a method to get data from a external URL using HTTP Get.

loaddata() {
  if (this.data) {
    // already loaded data
    return Promise.resolve(this.data);
  }
 
  return new Promise(resolve => {
    this.http.get('your external api to load data')
      .map(res => res.json())
      .subscribe(data => {
        // we've got back the raw data, now generate the core schedule data
        // and save the data for later reference
        this.data = data;
        resolve(this.data);
      });
  });
}

Now, Import the NewsService to your page using the following code,

import { NewsService } from '../../providers/news-service';

Include the provider inside @component

@Component({
  selector: 'page-page1',
  templateUrl: 'page1.html',
  providers: [NewsService]
})

And in your controller create a public variable to hold the data from the external server, create a news property, import the NewsService, and assign the NewsServiceto a property of the class. loadNews() will call the newsService.load method and assign the result of the promise in a news property of the class.

export class Page1 {
  public news: any;
  constructor(public newsService: NewsService) {
    this.loadNews();
 
  }
  loadNews() {
    this.newsService.load()
      .then(data => {
        console.log(data);
        this.news = data;
      });
  }
}

Now, ionic serve to run the application so that here when page1 loads, a external call will be made, you can check your network tab to verify the working.

Category: