繁体   English   中英

如何使用ModuleWithProviders导入Angular模块中的其他模块

[英]How to import other modules in Angular Module with ModuleWithProviders

我在模块中有一个服务。 我称之为AService和AModule:

  @Injectable()
  export class AService {
    constructor() { }
  }

  @NgModule({
    imports: [CommonModule],
    providers: [AService]
  })
  export class AModule {}

我在b模块内部有ab服务。 B服务取决于A服务:

  @Injectable()
  export class BService {
    constructor(
      private aService: AService
    ) { }
  }

对于B模块,我使用的是ModuleWithProviders:

  @NgModule({
    imports: [CommonModule, AModule]
  })
  export class BModule {
    public static forRoot(settings: any): ModuleWithProviders {
      return {
        ngModule: BModule,
        providers: [
          BService
        ]
      };
    }
  }

即使我正在导入AModule,我也没有为AService提供服务。 看起来像ModuleWithProviders,导入被忽略:

  Promise rejection: StaticInjectorError(AppModule)[BService -> AService]:
  ...
  No provider for AService!

让BModule依赖AModule的正确方法是什么?

我认为你是在做另一种方式。 您必须将ModuleWithProviders用于您共享指令和服务的共享模块,然后使用forRoot指令在您的应用程序模块中导入该模块。

您可以使用以下示例。

共享模块

import { NgModule, ModuleWithProviders } from '@angular/core';
@NgModule({
  declarations: [
    Pipes, Directives
  ],
  exports: [
    Pipes, Directives
  ]
})
export class SharedModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [ SomeService ]
    };
  }
} 

现在,在您的应用模块中导入您的共享模块。 应用模块

import { SharedModule } from './shared/shared.module';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    SharedModule.forRoot()
  ],
  bootstrap: [
    AppComponent
  ]
})
export class AppModule {}

您也可以在任何模块中导入该共享模块,而无需使用forRoot()

其他模块

import { SharedModule } from '../shared/shared.module';

// ...

@NgModule({
  imports: [
    CommonModule,
    SharedModule
  ],
  declarations: [
    // ...
  ]
})
export class SomeFeatureModule {}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM