I am curious about how the services from injected work in IONIC 2. Specifically, my question is regarding the number of instances that exist when one service is used in two or more controllers.
Previously, I asked a colleague who mentioned that IONIC 2 operates with the singleton pattern, but based on my testing, it seems otherwise.
Let's consider two controllers, A and B, along with a service SVC1:
Controller A
import { NavController, Platform } from 'ionic-angular';
import { PageB } from '../pageb/pageB';
import { SVC1 } from '../../providers/svc1';
@Component({
selector: 'page-a',
templateUrl: 'a.html',
providers: [SVC1]
})
export class PageA {
constructor(public navCtrl: NavController, platform: Platform, public svc: SVC1) {
}
onAddEventClicked(event): void {
this.navCtrl.push(PageB);
}
}
Controller B
import { NavController, Platform } from 'ionic-angular';
import { SVC1 } from '../../providers/svc1';
@Component({
selector: 'page-b',
templateUrl: 'b.html',
providers: [SVC1]
})
export class PageB {
constructor(public navCtrl: NavController, platform: Platform, public svc: SVC1) {
}
}
Service
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
@Injectable()
export class SVC1 {
constructor(public http: Http) {
console.log('creating another instance');
}
}
In this simple setup, PageA has a button that navigates to PageB. Both pages utilize the same service.
If the service were a singleton, the message "creating another instance" would only appear once. However, it shows up twice.
Why does this happen? Does IONIC use the singleton pattern to inject service references? Is there a way to ensure only one instance of my service?
Thank you
PS: Apologies for any language errors; I hope to improve over time.