Angular 2: how to make injection be singleton in application

I have an application @Injectablein my application that has been added as a provider to AppModule. I want to make sure that no one in my development team enters it into any other module. A single instance is enough, and it has complex logic that I do not want to run twice. Any ideas?

I know how DI works in angular 2, so answers like "Make sure it is added as a provider only in the App Module" will not help. :(

PAY ATTENTION that I want it to create some error during assembly or runtime if the service is provided to any other but AppModule.

+4
source share
1 answer

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. , .

+7

Source: https://habr.com/ru/post/1667373/


All Articles