I\'m trying to use \'providedin\' feature in Angular but receive the error \"StaticInjectorError(AppModule)[DashboardComponent -> DashboardService]:\"
@Injec
The stackblitz example posted by Stepan Suvorov does not work when using
providedIn: AppModule
because of a dependency issue, which causes AppModule
to be unresolved (undefined).
If you add a console.log(AppModule)
just above the @Injectable
decorator, the output is undefined
.
Note You cannot actually see that dependency issue on stackblitz, but you can if you replicate the project on a local angular cli, you'll see the following warnings.
WARNING in Circular dependency detected: src\app\app.component.ts -> src\app\my.service.ts -> src\app\app.module.ts -> src\app\app.component.ts
WARNING in Circular dependency detected: src\app\app.module.ts -> src\app\app.component.ts -> src\app\my.service.ts -> src\app\app.module.ts
WARNING in Circular dependency detected: src\app\my.service.ts -> src\app\app.module.ts -> src\app\app.component.ts -> src\app\my.service.ts
I don't think there is any point in using using AppModule
in providedIn
, you may as well use root
. But if you want your service to only be provided in a child module, this should work like in this stackblitz demo
Here is a related github issue
Note: when declaring an injectable service, if you use providedIn
with a module value, the specified module cannot be a module which declares a component which uses that service (quite a mouthful)
Finally I have found the solution: https://angular.io/guide/providers#providedin-and-ngmodules Service also should be mentioned in the providers section of module.
@NgModule({
imports: [CommonModule],
declarations: [DashboardComponent],
exports: [DashboardComponent],
providers: [DashboardService]
})
Demo has been corrected. Thank you guys!
See this for more information on the "additional module": https://www.youtube.com/watch?v=jigR_jBhDMs&feature=youtu.be
Sample code here: https://github.com/web-dave/provide-in-test
Discussion of the circular dependency issue here: https://github.com/web-dave/provide-in-test/issues/1
Make sure you have your module imported in the test like this:
beforeEach(() => TestBed.configureTestingModule({
imports: [DashboardModule]
}));