Important Update for Ionic2:
With the latest Ionic2 RC version, it is now recommended to include services in the providers
array within the @NgModule
. This configuration ensures that the services function as singletons, meaning that the same instance will be utilized throughout the entire application.
@NgModule({
declarations: [
MyApp,
// Pages
Page1,
Page2,
// Pipes
MyCustomPipe,
// Directives
MyCustomDirective,
],
imports: [
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
// Pages
Page1,
Page2
],
providers: [ DataService, NavigationService, Storage, ... ] // <- Include services here!
})
export class AppModule {}
Prior Answer (2.0.0-beta.8)
In earlier versions of Ionic2, specifically with release 2.0.0-beta.8, developers could utilize ionicBootstrap
to ensure service instances function as singletons
, maintaining consistency throughout the application.
The adjustments required were minimal; existing services remained unchanged:
/* Note the slight changes in imports */
import {Injectable} from "@angular/core";
import {Http} from "@angular/http";
import 'rxjs/Rx';
@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;
}
}
Rather than injecting services as a provider
within your Component
, which would create new instances each time the component
is loaded:
import {Component} from '@angular/core';
import {DataService} from './service';
@Component({
templateUrl: 'build/test.html'
/* This approach should no longer be followed */
/* providers: [DataService] */
})
export class TestPage {
constructor(data: DataService) {
data.retrieveData()
}
}
Simply incorporate the service in the ionicBootstrap
of your app.ts
, ensuring consistent usage of the same service instance across the application.
ionicBootstrap(MyApp, [DataService], {});
Recommended Approach per Angular Style Guide:
According to the Angular2 Style Guide,
Provide services to the Angular 2 injector at the highest-level component where they will be shared.
This strategy leverages the hierarchical nature of the Angular 2 injector.
By registering the service at the top level component, that instance is accessible to all child components under that parent.
This method is ideal when a service needs to share methods or state.
Moreover,
While it may work, not adhering to this guideline is suboptimal. It's advised to use the bootstrap provider option primarily for configuring and overriding Angular’s own pre-registered services, such as routing support.
Therefore, instead of registering the service within ionicBootstrap
, it is best practice to register it in the top-most component of our App if we seek to maintain the same service instance globally:
@Component({
templateUrl: 'build/app.html',
directives: [...],
providers: [..., DataService]
})
class MyApp{
// ...
}