【发布时间】:2017-07-20 13:45:59
【问题描述】:
我正在查看有关 NgModule 的官方 Angular 文档 (https://angular.io/guide/ngmodule#configure-core-services-with-coremoduleforroot) 在页面末尾提供的示例中,有文件 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 }
]
};
}
}
这是一个核心模块,通过使用构造函数和 forRoot 方法 我们确定核心模块只导入一次,并且我们只有一个所提供服务的实例。
- @NgModule({...}) 中的 providers 数组和 forRoot 方法中的 providers 数组有什么区别?
- 我应该在 @NgModel 部分还是在核心模块中提供我的单例服务?
【问题讨论】:
标签: angular