Reputation: 5161
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 a b 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?
Upvotes: 3
Views: 3122
Reputation: 1303
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 {}
Upvotes: 4