Using angular 2 ajax in ionic 2

Issue

I am running an angular 2 application in ionic 2 and I am trying to get JSON data from a server. What is the process for making a call to the server and receive JSON so my application can parse it? Are there any things I should be aware of when making the calls?

Solution

You need to inject an instance of Http into the element (component or service) where you want to execute the request.

For example with ES6 within a component:

(...)
import {Http} from 'angular2/http';
import 'rxjs/Rx';

@Page({
  templateUrl: 'build/pages/page3/page3.html'
})
export class Page3 {
  constructor(http) {
    http.get('data.json').map(res => res.json()).subscribe(
      (data) => {
        this.data = data;
      }
    );
  }

  static get parameters() {
    return [[Http]];
  }
}

Note that you can also use the async pipe. See this link for more details:

Don’t forget to specify the providers for HTTP into your application class:

(...)
import {HTTP_PROVIDERS} from 'angular2/http';

@App({
  template: `
    (...)
  `,
  config: {},
  providers: [ HTTP_PROVIDERS ]
})
export class MyApp {
  (...)
}

Answered By – Thierry Templier

Answer Checked By – Cary Denson (AngularFixing Admin)

Leave a Reply

Your email address will not be published.