How to use angular 2 service with Ionic 2?

There is no use of Bootstrap() in Ionic2, only use of @App to declare your app.
You still need to declare your service in your @Page component.

Create your service

import {Injectable} from "angular2/core";
import {Http} from "angular2/http";

@Injectable()
export class DataService {
  constructor(http: Http) {
    this.http = http;
    this.data = null;
  }

  retrieveData() {
    this.http.get('./mocks/test.json')
    .subscribe(data => {
      this.data = data;
    });
  }

  getData() {
    return this.data;
  }
}

Then use it in your @Page

import {Page} from 'ionic/ionic';
import {DataService} from './service';

@Page({
  templateUrl: 'build/test.html',
  providers: [DataService]
})
export class TestPage {
  constructor(data: DataService) {
    data.retrieveData()
  }
}

Leave a Comment