Angular supports one instance for each provider.
Make sure that you provide the service only once, and DI guarantees that there will be only one instance in your application.
If you provide the service on comonent @Component({ ..., providers: [...]}), then there will be as many instances as there are instances of the components.
If you provide a service only providersfrom AppModuleor providersfor modules imported into AppModule, then for your entire application there will be only one instance:
@NgModule({
providers: [...],
imports: [...]
})
export class AppModule {}
- . , , DI.
forRoot() , forRoot(), providers AppModule
@NgModule({
providers: [...],
imports: [LazyLoadedModuleWithSingltonProvider.forRoot()]
})
export class AppModule {}
, ,
@Injectable()
export class MyService {
private static instanceCounter = 0;
private instanceNumber = instanceCounter++;
constructor() {
if(this.instanceNumber > 0) {
throw 'MyService must be kept a singleton but more than one instance was created';
}
}
}
singleton CoreModule , AppModule
https://angular.io/docs/ts/latest/guide/ngmodule.html#!#prevent-reimport
AppModule CoreModule. , .