Angular 4 are services provided in a core module singleton for real?

Viewed 6622

I'm trying to understand core module and singleton services in angular 4. The official documentation (https://angular.io/guide/ngmodule) says the following things:

UserService is an application-wide singleton. You don't want each module to have its own separate instance. Yet there is a real danger of that happening if the SharedModule provides the UserService.

CoreModule provides the UserService. Angular registers that provider with the app root injector, making a singleton instance of the UserService available to any component that needs it, whether that component is eagerly or lazily loaded.

We recommend collecting such single-use classes and hiding their details inside a CoreModule. A simplified root AppModule imports CoreModule in its capacity as orchestrator of the application as a whole.

import { CommonModule }      from '@angular/common';
import { TitleComponent }    from './title.component';
import { UserService }       from './user.service';
import { ModuleWithProviders, NgModule, Optional, SkipSelf }       from '@angular/core';
@NgModule({
  imports:      [ CommonModule ],
  declarations: [ TitleComponent ],
  exports:      [ TitleComponent ],
  providers:    [ UserService ]
})
export class CoreModule {
    constructor (@Optional() @SkipSelf() parentModule: CoreModule) { ... }
}

So I'm using the Core Module providing singleton services, and the constructor

constructor (@Optional() @SkipSelf() parentModule: CoreModule) { ... }

prevent to import the Core Module more than one time.

1) BUT, what if I provide the UserService in another module (e.g in a lazy-loading module) ? This lazy-loaded module has a new instance of the service?

And about forRoot method:

@NgModule({
  imports:      [ CommonModule ],
  providers:    [ UserService ]
})
export class CoreModule {
}

static forRoot(config: UserServiceConfig): ModuleWithProviders {
  return {
    ngModule: CoreModule,
    providers: [
      {provide: UserServiceConfig, useValue: config }
    ]
  };
}
}

2) If I import the CoreModule using CoreModule.forRoot() in the AppModule, what happen to the UserService ? Is it provided too?

Thanks

3 Answers
Related