Error: “Encountered undefined provider! Usually th

2020-02-02 11:52发布

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 
...

14条回答
smile是对你的礼貌
2楼-- · 2020-02-02 12:15

in my case I just deleted the @Injectable() decorator from my service(cause it didn't need any services to be injected in it)

查看更多
看我几分像从前
3楼-- · 2020-02-02 12:15

in my case, very simple, it was really undefined provider in the module definition.
Because the lib I used, had an option to dynamically change their providers and it was wrong configured, so it loaded undefined as providers.

查看更多
Summer. ? 凉城
4楼-- · 2020-02-02 12:16

Got this error running --prod.

You can't import things like that:

import { MyService } from '.';

You should use the full path

import { MyService } from './my.service'
查看更多
仙女界的扛把子
5楼-- · 2020-02-02 12:23

Sometime this issue occurred because of some dependency in third party api used in angular app. I faced same issue and resolved it using following steps:

  1. Removed package.lock.json file
  2. Deleted node_modules folder
  3. Again run npm install
  4. Run "ng build --prod" These steps will resolve your issue.
查看更多
太酷不给撩
6楼-- · 2020-02-02 12:25

I got my way around this by flattening all of the barrel imports(which kinda defeats the purpose of using barrel files in the first place, but I can't afford losing more time on this).

查看更多
可以哭但决不认输i
7楼-- · 2020-02-02 12:27

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 {
}
查看更多
登录 后发表回答