Angular DI Error - EXCEPTION: Can't resolve all parameters

倾然丶 夕夏残阳落幕 提交于 2019-11-26 00:46:00

问题


I\'ve built a basic app in Angular, but I have encountered a strange issue where I cannot inject a service into one of my components. It injects fine into any of the three other components I have created however.

For starters, this is the service:

import { Injectable } from \'@angular/core\';

@Injectable()
export class MobileService {
  screenWidth: number;
  screenHeight: number;

  constructor() {
    this.screenWidth = window.outerWidth;
    this.screenHeight = window.outerHeight;

    window.addEventListener(\"resize\", this.onWindowResize.bind(this) )
  }

  onWindowResize(ev: Event) {
    var win = (ev.currentTarget as Window);
    this.screenWidth = win.outerWidth;
    this.screenHeight = win.outerHeight;
  }

}

And the component that it refuses to work with:

import { Component, } from \'@angular/core\';
import { NgClass } from \'@angular/common\';
import { ROUTER_DIRECTIVES } from \'@angular/router\';

import {MobileService} from \'../\';

@Component({
  moduleId: module.id,
  selector: \'pm-header\',
  templateUrl: \'header.component.html\',
  styleUrls: [\'header.component.css\'],
  directives: [ROUTER_DIRECTIVES, NgClass],
})
export class HeaderComponent {
  mobileNav: boolean = false;

  constructor(public ms: MobileService) {
    console.log(ms);
  }

}

The error I get in the browser console is this:

EXCEPTION: Can\'t resolve all parameters for HeaderComponent: (?).

I have the service in the bootstrap function so it has a provider. And I seem to be able to inject it into the constructor of any of my other components without issue.


回答1:


Import it from the file where it is declared directly instead of the barrel.

I don't know what exactly causes the issue but I saw it mentioned several times (probably some kind of circular dependency).

It should also be fixable by changing the order of the exports in the barrel (don't know details, but was mentioned as well)




回答2:


In addition to the previous answers given, it seems this error is thrown as well when your injectable service is missing the actual @Injectable() decorator. So before you debug the cyclic dependency thing and the order of your imports/exports, do a simple check whether your service actually has @Injectable() defined.

This applies to the current Angular latest, Angular 2.1.0.

I opened an issue on this matter.




回答3:


As of Angular 2.2.3 there is now a forwardRef() utility function that allows you to inject providers that have not yet been defined.

By not defined, I mean that the dependency injection map doesn't know the identifier. This is what happens during circular dependencies. You can have circular dependencies in Angular that are very difficult to untangle and see.

export class HeaderComponent {
  mobileNav: boolean = false;

  constructor(@Inject(forwardRef(() => MobileService)) public ms: MobileService) {
    console.log(ms);
  }

}

Adding @Inject(forwardRef(() => MobileService)) to the parameter of the constructor in the original question's source code will fix the problem.

References

Angular 2 Manual: ForwardRef

Forward references in Angular 2




回答4:


WRONG #1: Forgetting Decorator:

//Uncaught Error: Can't resolve all parameters for MyFooService: (?).
export class MyFooService { ... }

WRONG #2: Omitting "@" Symbol:

//Uncaught Error: Can't resolve all parameters for MyFooService: (?).
Injectable()
export class MyFooService { ... }

WRONG #3: Omitting "()" Symbols:

//Uncaught Error: Can't resolve all parameters for TypeDecorator: (?).
@Injectable
export class MyFooService { ... }

WRONG #4: Lowercase "i":

//Uncaught ReferenceError: injectable is not defined
@injectable
export class MyFooService { ... }

WRONG #5: You forgot: import { Injectable } from '@angular/core';

//Uncaught ReferenceError: Injectable is not defined
@Injectable
export class MyFooService { ... }

CORRECT:

@Injectable()
export class MyFooService { ... }



回答5:


As already stated, the issue is caused by the export ordering within the barrel which is caused by circular dependencies.

A more detailed explanation is here: https://stackoverflow.com/a/37907696/893630




回答6:


I also encountered this by injecting service A into service B and vice versa.

I think it's a good thing that this fails fast as it should probably be avoided anyway. If you want your services to be more modular and re-usable, it's best to avoid circular references as much as possible. This post highlights the pitfalls surrounding that.

Therefore, I have the following recommendations:

  • If you feel the classes are interacting too often (I'm talking about feature envy), you might want to consider merging the 2 services into 1 class.
  • If the above doesn't work for you, consider using a 3rd service, (an EventService) which both services can inject in order to exchange messages.



回答7:


For the benefit of searchers; I got this error. It was simply a missing @ symbol.

I.e. This produces the Can't resolve all parameters for MyHttpService error.

Injectable()
export class MyHttpService{
}

Adding the missing @ symbol fixes it.

@Injectable()
export class MyHttpService{
}



回答8:


In my case, I needed to add import "core-js/es7/reflect"; to my application to make @Injectable work.




回答9:


You get this error if you have service A that depends on a static property / method of service B and the service B itself depends on service A trough dependency injection. So it's a kind of a circular dependency, although it isn't since the property / method is static. Probably a bug that occurs in combination with AOT.




回答10:


In addition to the missing @Injectable() decorator

Missing @Injectable() decorator in abstract class produced the Can't resolve all parameters for service: (?) The decorator needs be present in MyService as well as in the derived class BaseService

//abstract class
@Injectable()
abstract class BaseService { ... }

//MyService    
@Injectable()
export class MyService extends BaseService {
.....
}



回答11:


In my case, it happened because I didn't declare the type for a constructor parameter.

I had something like this:

constructor(private URL, private http: Http) { }

and then changing it to the code below solved my problem.

constructor(private URL : string, private http: Http) {}



回答12:


Another possibility is not having emitDecoratorMetadata set to true in tsconfig.json

{
  "compilerOptions": {

     ...

    "emitDecoratorMetadata": true,

     ...

    }

}



回答13:


Removing parameters from injectable constructor() method solved it for my case.




回答14:


for me it was just lack of () in @Injectable. Proper is @Injectable()




回答15:


In my case it was because of the plugin Augury, disable it will work fine. Alternative option is aot, also works.

all credits to @Boboss74 , he posted the answer here: https://github.com/angular/angular/issues/23958




回答16:


Well for me the issue was even more annoying, I was using a service within a service and forgot to add it as dependency in the appModule! Hope this helps someone save several hours breaking the app down only to build it back up again




回答17:


You have to add providers array in @Component decorator or in the module where your component is declared. Inside component you can do as below:

@Component({
  moduleId: module.id,
  selector: 'pm-header',
  templateUrl: 'header.component.html',
  styleUrls: ['header.component.css'],
  directives: [ROUTER_DIRECTIVES, NgClass],
  providers: [MobileService]
})



回答18:


In my case passing wrong parameters to constructor generates this error, basic idea about this error is that you unknowingly passed some wrong args to any function.

export class ProductComponent {
    productList: Array<Product>;

    constructor(productList:Product) { 
         // productList:Product this arg was causing error of unresolved parameters.
         this.productList = [];
    }
}

I solved this by just removing that argument.




回答19:


For me, I got this error when I mistakenly disabled this import in the polyfills.ts file , you need to ensure it is imported to avoid that error.

/** Evergreen browsers require these. **/
// Used for reflect-metadata in JIT. If you use AOT (and only Angular decorators), you can remove.
import 'core-js/es7/reflect';



回答20:


In my case I was trying to extend "NativeDateAdapter" in order to override "format(date: Date, displayFormat: Object)" method.

In AngularMaterial-2 DatePicker .

So basically I forgot to add @Injectable anotation.

After I add this to my "CustomDateAdapter" class:

@Injectable({
  providedIn: 'root'
})

Error has gone.




回答21:


I have encountered this error by mistyping the service's name, i.e. constructor (private myService: MyService).

For misspelled services, I was able to determine which service was the problem (I had several listed in the constructor) by inspecting the page in Chrome->Console. You will see as part of the message a "parameter" array list by displaying object Object, object Object, ? (or something like that). Notice where the "?" is and that is the position of the service that is causing the problem.




回答22:


Although the ordering of exported classes from within barrels may have been mentioned, the following scenario may also produce the same effect.

Suppose you have classes A, B, and C exported from within the same file where A depends on B and C:

@Injectable()
export class A {
    /** dependencies injected */
    constructor(private b: B, private c: C) {}
}

@Injectable()
export class B {...}

@Injectable()
export class C {...}

Since the dependent classes (i.e. in this case classes B and C) are not yet known to Angular, (probably at run-time during Angular's dependency injection process on class A) the error is raised.

Solution

The solution is to declare and export the dependent classes before the class where the DI is done.

i.e. in the above case the class A is declared right after its dependencies are defined:

@Injectable()
export class B {...}

@Injectable()
export class C {...}

@Injectable()
export class A {
    /** dependencies injected */
    constructor(private b: B, private c: C) {}
}



回答23:


In my case, I was exporting a Class and an Enum from the same component file:

mComponent.component.ts:

export class MyComponentClass{...}
export enum MyEnum{...}

Then, I was trying to use MyEnum from a child of MyComponentClass. That was causing the Can't resolve all parameters error.

By moving MyEnum in a separate folder from MyComponentClass, that solved my issue!

As Günter Zöchbauer mentioned, this is happening because of a service or component is circularly dependent.




回答24:


If your service is defined in the same file as a component (that consumes it) and the service is defined after the component in the file you may get this error. This is due to the same 'forwardRef' issue others have mentioned. At this time VSCode isn't great about showing you this error and the build compiles successfully.

Running the build with --aot can mask this problem due to the way the compiler works (probably related to tree shaking).

Solution: Make sure the service is defined in another file or before the component definition. (I'm not sure if forwardRef can be used in this case, but it seems clumsy to do so).

If I have a very simple service that is very strongly tied to a component (sort of like a view model) - eg. ImageCarouselComponent, I may name it ImageCarouselComponent.service.ts so it doesn't get all mixed up with my other services.




回答25:


In my case it was a circular reference. I had MyService calling Myservice2 And MyService2 calling MyService.

Not good :(




回答26:


In my case, the reason was the following:

  • my injectable service A extended another class B
  • B had a constructor which required an argument
  • I hadn't defined any constructor in A

As a consequence, when trying to create an object A, the default constructor failed. I have no idea why this wasn't a compile error.

I got it fixed by simply adding a constructor in A, which correctly called B's constructor.




回答27:


This answer might be very helpful for this problem. In addition, for my case, exporting the service as default was the cause.

WRONG:

@Inject()
export default class MobileService { ... }

CORRECT:

@Inject()
export class MobileService { ... }



回答28:


This can be a really difficult issue to debug due to the lack of feedback in the error. If you are concerned about an actual cyclic dependency, here's the most important thing to look at in the stack trace a) the name of the service b) the constructor parameter in that service that has a question mark e.g. if it looks like this:

can't resolve all parameters for AuthService: ([object Object], [object Object], [object Object], [object Object], ?)

then it means the 5th parameter is a service that also depend on AuthService. i.e. question mark, means it wasn't resolved by DI.

From there, you just need to decouple the 2 services by restructuring the code.




回答29:


When using barrel imports - consider importing injectables first as a rule of thumb.




回答30:


It happens when referring an interface as well.

Changing interface for class fixed it, working with and without @Inject.



来源:https://stackoverflow.com/questions/37997824/angular-di-error-exception-cant-resolve-all-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!