[angular] Error when trying to inject a service into an angular component "EXCEPTION: Can't resolve all parameters for component", why?

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.

This question is related to angular typescript dependency-injection

The answer is


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


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.


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


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

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

Sometimes this happens when you declared Angular's inbuilt module(HttpClientModule, HttpErrorResponse etc) in app.module.js. I also faced the same issue but resolved now.

The mistake I did was mention HttpClientModule into Providers instead of Import of angular Module


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';

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) {}

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.


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


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


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


for angular 6 and newer versions, try

@Injectable({
  providedIn: 'root'
})

..right above your service class with no other lines in between

advantages

  • no need to add the service to any module (will be "auto-discovered")
  • service will be a singleton (since it will be injected into root)

[angular docs]


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{
}

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.


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


For me this was because i stopped using the -aot flag whilst trying to make the compile time faster.

 ng serve -aot

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.

Im my case, add "emitDecoratorMetadata" and "esModuleInterop" solved the problem.

https://github.com/thymikee/jest-preset-angular/issues/288


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.


If you try to inject an interface, this error occurs as well:

Somewhere:

export const MY_SERVICE = new InjectionToken<MyService>('MY_SERVICE');

export interface MyService {
  // ...
}

@Injectable()
export class MyServiceImpl implements MyService {
  // ...
}

Incorrect:

  constructor(
    private myService: MyService
  ) {}

Correct:

  constructor(
    @Inject(MY_SERVICE) private myService: MyService
  ) {}

It happens when referring an interface as well.

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


For me, it was because I had an empty line between my @Component decorator and my Component class. This caused the decorator not to get applied to the class.


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

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) {}
}

In my case, that was the TypeScript version that I upgraded to a major version and assignation assertions that I added to some Class properties.

Reverting the changes solved this for me. (details here)


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


to me stopping the application and issuing ng serve fixed the problem


In my case I missed to call the constructor of the class I inherited from.

Before:

@Component({ ... })
export class ComponentA extends ComponentParent {
  // ...
}

After:

@Component({ ... })
export class ComponentA extends ComponentParent {
  constructor(protected route: ActivatedRoute, protected store$: Store<AppState>) {
    super(route, store$);
  }
  // ...
}

In may case the error was caused by upgrading the @angular-devkit/build-angular to ~0.803.*. See https://github.com/angular/angular-cli/issues/15892 for the details.


In my case fix was replacing relative path with absolute before

import {Service} from './service';

after

import {Service} from 'src/app/services/service';

Looks like typescript/angular issue


You can try running the following command again:

ng serve --open


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

{
  "compilerOptions": {

     ...

    "emitDecoratorMetadata": true,

     ...

    }

}

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.


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


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.


In my case, I took a dependency on a service that had no dependencies and therefore I did not add a constructor() function to the service class. I added a parameterless constructor to the dependent service class and everything started working.


_x000D_
_x000D_
import {Injector} from '@angular/core';
import {ServiceA} from './service-a';

@Component({
  // ... 
})
class MyComp {
  constructor(private injector: Injector) {
     const serviceA = injector.get(ServiceA);
  }
}
_x000D_
_x000D_
_x000D_


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

Not good :(


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.


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.


Gotcha!

If none of the above answers helped you, maybe you are importing some element from the same file where a component is injecting the service.

I explain better:

This is the service file:

// your-service-file.ts
import { helloWorld } from 'your-component-file.ts'

@Injectable()
export class CustomService() {
  helloWorld()
}

This is the component file:

@Component({..})
export class CustomComponent {
  constructor(service: CustomService) { }
}

export function helloWorld() {
  console.log('hello world');
}

So it causes problems even if the symbol isn't inside the same component, but just inside the same file. Move the symbol (it can be a function, a constant, a class and so on...) elsewhere and the error will fade away


Anuglar import paths are case sensitive.Check if your service paths are correct everywhere you use service and also check the letter cases to be correct and identical everywhere.


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.


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]
})

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to typescript

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type?

Examples related to dependency-injection

Are all Spring Framework Java Configuration injection examples buggy? Passing data into "router-outlet" child components ASP.NET Core Dependency Injection error: Unable to resolve service for type while attempting to activate Error when trying to inject a service into an angular component "EXCEPTION: Can't resolve all parameters for component", why? org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController' How to inject window into a service? How to get bean using application context in spring boot Resolving instances with ASP.NET Core DI from within ConfigureServices How to inject a Map using the @Value Spring Annotation? WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default