Here's a somewhat useless error I'm getting in my Angular / TypeScript application. Until someone makes the error message better, what can we do about this? What are the most likely situations that cause this to happen?
Uncaught Error: Encountered undefined provider! Usually this means you have a circular dependencies (might be caused by using 'barrel' index.ts files.
at Object.syntaxError
at eval at Array.forEach (native) [<root>]
at CompileMetadataResolver._getProvidersMetadata
at CompileMetadataResolver.getNgModuleMetadata
at CompileMetadataResolver.getNgModuleSummary
at eval
...
It is very hard to tell from the error message which provider causes this issue. The way I managed to debug this is the following:
console.log('type', type);
in order to see in which file is the undefined provider (You can also console log other relevant variables there).For me, I just restart the ng serve
One possibility is trying to declare a service and module in the same file, and declaring the module before the service:
import {Injectable, NgModule} from '@angular/core';
@NgModule({providers: [FooService]}) // WRONG: used before declared
export class FooModule {
}
@Injectable()
export class FooService {
}
You can fix this by declaring the service first, or you can use forwardRef
like this:
import {forwardRef, Injectable, NgModule} from '@angular/core';
@NgModule({providers: [forwardRef(() => FooService)]})
export class FooModule {
}
@Injectable()
export class FooService {
}
I have no reputation yet to comment on https://stackoverflow.com/a/51304428/2549593 But better add following:
console.error('\ntype: ', type, '\nproviders: ', (providers || []).map(p => p && (p.name || p.useClass || p.useValue || p.useFactory || p.useExisting)));
It will display providers list and module with the problem, so you can open it, and check this providers list: one which was marked as undefined - should be fixed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With