Angular6使用forRoot-注册单一实例服务

4次阅读

共计 866 个字符,预计需要花费 3 分钟才能阅读完成。

假如我们有一个 shareModule 来存放公用的组件 (Component)、指令 (Directive)、管道 (Pipe)、服务(Service),为避免各个子模块引用 shareModule 时造成 App 中有多个一样的单一实例服务的问题。我们可以在 shareModule 中建立同意的 App 层级的服务。

ShareModule

import {NgModule, ModuleWithProviders} from '@angular/core';

@NgModule({
    imports: [
        HttpModule,
        JsonpModule,
        ...
    ],

    declarations: [
        ShowItDirective,
        ...
    ],
    exports: [
        ShowItDirective,
        ...
    ]
})
export class ShareModule{
    // 给 shareModule 添加 forRoot
    static forRoot(): ModuleWithProviders {
        return {
            ngModule: ShareModule,
            providers: [
                MessageService,
                NotifyService,
                ... any service
            ],

        };
    }
}

AppModule

@NgModule({
  declarations: [AppComponent,],
  imports: [
    // 使用
    ShareModule.forRoot(),],
  providers: [ ],
  bootstrap: [AppComponent]
})
export class AppModule {}

这样 ShareModule 中每一个 service 都只在 app 中注册了一个实例,也避免了每次使用 service 都要 provider 的问题。

ERROR NullInjectorError: StaticInjectorError(AppModule)[SurveyComponent -> PermissionCheckerService]: 
NullInjectorError: No provider for PermissionCheckerService!

正文完
 0