VISHAL DAGA VISHAL DAGA - 3 months ago 35
TypeScript Question

How to use angular 2 service with Ionic 2

I am new to Ionic 2.
I read in angular 2 docs, that service needs to be injected while bootstrap application. But could not see any bootstrap thing while going through Ionic 2 tutorial.

Any help is highly appreciated.

Answer

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()
  }
}