简体   繁体   中英

How to import other modules in Angular Module with ModuleWithProviders

I have a service inside a module. I call them AService and AModule:

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

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

I have ab service inside of b module. B service depends on A service:

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

For B module, I am using ModuleWithProviders:

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

I am getting no provider for AService even though I am importing AModule. It seems like with ModuleWithProviders, the imports are ignored:

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

What is the proper way to have BModule depend on AModule?

I think you are doing it the other way. You will have to use ModuleWithProviders for your shared module, in which you are sharing your directives and services, then import that module in your app module using forRoot directive.

You can use the following example.

Shared Module

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

Now Import your shared module in your app module. App Module

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

You can also import that shared module in any module without using forRoot()

Other Modules

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

// ...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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