I was looking at the official angular documentation about NgModule (https://angular.io/guide/ngmodule#configure-core-services-with-coremoduleforroot) and in the example provided at the end of the page there's the file core.module.ts
import { ModuleWithProviders, NgModule, Optional, SkipSelf } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TitleComponent } from './title.component';
import { UserService } from './user.service';
import { UserServiceConfig } from './user.service';
@NgModule({
imports: [ CommonModule ],
declarations: [ TitleComponent ],
exports: [ TitleComponent ],
providers: [ UserService ]
})
export class CoreModule {
constructor (@Optional() @SkipSelf() parentModule: CoreModule) {
if (parentModule) {
throw new Error(
'CoreModule is already loaded. Import it in the AppModule only');
}
}
static forRoot(config: UserServiceConfig): ModuleWithProviders {
return {
ngModule: CoreModule,
providers: [
{provide: UserServiceConfig, useValue: config }
]
};
}
}
This is a Core Module, and by using the constructor and the forRoot method we're sure the core module is imported only once, and we have only one instance of the services provided.
- What's the difference between the providers array in the @NgModule({...}) and the providers array in the method forRoot?
- Should I provide my singleton services in the @NgModel section or in the Core Module?