Reputation: 305
I've been playing with DI in Angular and can't figure out why I run into an error when specifying a service to be provided in module via providedIn
.
First off, I created SharedModule
, declared there SharedComponent
and configured SharedService
as follows:
// shared.module.ts
@NgModule({
declarations: [SharedComponent],
exports: [SharedComponent]
})
export class SharedModule {}
// shared.service.ts
@Injectable({
providedIn: SharedModule
})
export class SharedService {
prop = Math.random();
}
Then I added one lazy module, included SharedModule
into imports
property on NgModule
decorator factory of both AppModule
and LazyModule
and configured my routing strategy. Here is the setup:
// app.module.ts
const routes: Routes = [
{ path: '', redirectTo: 'eager', pathMatch: 'full' },
{ path: 'eager', component: SharedComponent },
{ path: 'lazy', loadChildren: './lazy.module#LazyModule' }
];
const routing: ModuleWithProviders = RouterModule.forRoot(routes);
@NgModule({
imports: [
routing,
BrowserModule,
SharedModule
],
declarations: [AppComponent, EagerComponent],
bootstrap: [AppComponent],
providers: [{provide: APP_BASE_HREF, useValue: '/'}]
})
export class AppModule {}
// lazy.module.ts
const routes: Routes = [
{ path: '', component: SharedComponent }
];
export const routing: ModuleWithProviders = RouterModule.forChild(routes);
@NgModule({
imports: [
SharedModule,
routing
],
})
export class LazyModule {}
As a result, I get the following error:
Uncaught Error: Can't resolve all parameters for SharedComponent: (?).
But if I comment providedIn: SharedModule
and declare a provider for the SharedService
within the SharedModule
it works like a charm:
// shared.module.ts
@NgModule({
declarations: [SharedComponent],
exports: [SharedComponent],
providers: [SharedService]
})
export class SharedModule {}
Please see the StackBlitz demo.
Upvotes: 0
Views: 88
Reputation: 305
When I ran it locally on my machine it gave me console.warn
saying there is a circular dependency.
Circular dependency detected: src\app\shared.component.ts -> src\app\shared.service.ts -> src\app\shared.module.ts -> src\app\shared.component.ts
I fixed it as describes this guide by adding additional module intended for the service. So it's best not to rely on StackBlitz when it comes to debugging.
Upvotes: 0