Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: "Encountered undefined provider! Usually this means you have a circular dependencies"

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 
...
like image 596
Alexander Taylor Avatar asked Mar 24 '17 20:03

Alexander Taylor


4 Answers

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:

  • I went into the node_modules@angular\compiler\bundles\compiler.umd.js file
  • I found the line where it says: "Encountered undefined provider! Usually this means you have a circular dependencies. This might be caused by using 'barrel' index.ts files."
  • One line before I added console.log('type', type); in order to see in which file is the undefined provider (You can also console log other relevant variables there).
  • In the relevant file I found the 'barrel' import that caused the issue, and replaced it with exact file path import.
like image 59
Ophir Bushinsky Avatar answered Nov 12 '22 21:11

Ophir Bushinsky


For me, I just restart the ng serve

like image 44
Václav Mikeska Avatar answered Nov 12 '22 22:11

Václav Mikeska


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 {
}
like image 22
Alexander Taylor Avatar answered Nov 12 '22 20:11

Alexander Taylor


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

like image 7
Andrew Spoda Avatar answered Nov 12 '22 21:11

Andrew Spoda