/ javascript

Injecting Services in Angular 2 and Ionic 2

Create a service:

import {Injectable} from 'angular2/core';

export class MyService {
    constructor(http: Http) {
        // initalize things
    doSomething() {
        // do something

Injecting the newly created service per component

In vanilla Angular 2.0, as well as in Ionic 2 applications, you need to import the service class and add it to the list of providers on the @Component / @Page metadata. This will create a new instance of the injected class per component.

import {Page} from 'ionic-angular';
import {MyService} from '../../services/my-service';

  templateUrl: 'build/pages/home/home.html',
  providers: [MyService]
export class HomePage {
    constructor(mediumService: MediumService) {
        // The newly instantiated service will be provided here

Injecting a singleton instance of our new service

Coming from version 1.0, Angular offers a bootstrap function, which helps manually set up an application. In Angular 1.0, the bootstrap function is usually used for starting an application without explicitly placing ng-app on a DOM element, i.e. starting the application at a later point in time.

In Angular 2.0, calling bootstrap is the default way of setting up an application. When creating a component that will serve as the main starting point of your application, simply add the component as the first parameter of the bootstrap function. Here is modified example, based on the official Angular 2.0 docs:

import {MyService} from '../../services/my-service';

	selector: 'my-app', template: 'Hello {{ name }}!'
class MyApp {
	name: string = 'World';

function main() {
	return bootstrap(MyApp, [MyService /* and other dependencies, you want to instantiate globally */]);

Ionic 2 does not explicitly work with bootstrap, but requres at least one component, decorated with an @App decorator To inject a dependency, which should be avaiable as a singleton to all components across the application, add the dependency to the list of providers in your main app component, and simply do not add it to any provider list anywhere else. If you do so, the single dependency instance will be provided as an optional constructor paramater to every component. Here is an example from a sample Ionic 2 app:

	templateUrl: 'build/app.html',
	providers: [ConferenceData, UserData]
class ConferenceApp {
	// ...

And the ConferenceDatainstance will be available in every other component, without an explicit declaration:

import {ConferenceData} from '../../providers/conference-data';

	templateUrl: 'build/pages/schedule/schedule.html'
export class SchedulePage {
	static get parameters() {
		return [[IonicApp], [NavController], [ConferenceData], [UserData]];

	constructor(confData: ConferenceData) {

		// confData will the single instance, declared into your ConferenceApp
		this.confData = confData;