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)