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

AngularTypescriptDependency Injection

Angular Problem Overview


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.

Angular Solutions


Solution 1 - Angular

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)

Solution 2 - Angular

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.

Solution 3 - Angular

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

Solution 4 - Angular

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

Solution 5 - Angular

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

Solution 6 - Angular

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.

Solution 7 - Angular

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

Solution 8 - Angular

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

{
  "compilerOptions": {

     ...

    "emitDecoratorMetadata": true,

     ...

    }

}

Solution 9 - Angular

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

Solution 10 - Angular

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

Solution 11 - Angular

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.

Solution 12 - Angular

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

Solution 13 - Angular

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

Solution 14 - Angular

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

Solution 15 - Angular

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

Solution 16 - Angular

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

Solution 17 - Angular

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

Solution 18 - Angular

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.

Solution 19 - Angular

Adding Injectable solved my problem:

Error code

import { Observable } from 'rxjs';
import { io } from 'socket.io-client';
import { HttpClient } from '@angular/common/http';

export class Chat {

After fix

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { io } from 'socket.io-client';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class Chat {

Solution 20 - Angular

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.

Solution 21 - Angular

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

Solution 22 - Angular

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.

Solution 23 - Angular

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

Solution 24 - Angular

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.

Solution 25 - Angular

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

Solution 26 - Angular

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

Solution 27 - Angular

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.

Solution 28 - Angular

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.

Solution 29 - Angular

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

Not good :(

Solution 30 - Angular

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.

Solution 31 - Angular

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]

Solution 32 - Angular

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.

Solution 33 - Angular

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

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

Solution 34 - Angular

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

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

Solution 35 - Angular

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

Solution 36 - Angular

It happens when referring an interface as well.

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

Solution 37 - Angular

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

Solution 38 - Angular

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

 ng serve -aot

Solution 39 - Angular

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.

Solution 40 - Angular

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.

Solution 41 - Angular

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)

Solution 42 - Angular

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

Solution 43 - Angular

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$);
  }
  // ...
}

Solution 44 - Angular

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

Solution 45 - Angular

You can try running the following command again:

ng serve --open

Solution 46 - Angular

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.

Solution 47 - Angular

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

Solution 48 - Angular

The thing is that elements within a module should use relative imports for elements that are part of the same module; they should never import through the module’s public API barrel (or barrels in general btw).

The problem with that import is that if something that depends on the service is loaded first in the barrel (directly or not), then the DI system will fail since the service has not been declared yet and thus can’t be resolved.

Try changing the import from absolute:

import { UserService } from 'src/app/users/user.service';

To Relative:

import { UserService } from '../../users/user.service';

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKeith OttoView Question on Stackoverflow
Solution 1 - AngularGünter ZöchbauerView Answer on Stackoverflow
Solution 2 - AngularJ.P. ten BergeView Answer on Stackoverflow
Solution 3 - AngularReactgularView Answer on Stackoverflow
Solution 4 - AngularKANJICODERView Answer on Stackoverflow
Solution 5 - AngularMichaelView Answer on Stackoverflow
Solution 6 - AngularStephen PaulView Answer on Stackoverflow
Solution 7 - AngularJsAndDotNetView Answer on Stackoverflow
Solution 8 - AngularStewart_RView Answer on Stackoverflow
Solution 9 - AngularBartView Answer on Stackoverflow
Solution 10 - AngularAJ RichardsonView Answer on Stackoverflow
Solution 11 - AngularM KView Answer on Stackoverflow
Solution 12 - AngularAlf MohView Answer on Stackoverflow
Solution 13 - Angularotiai10View Answer on Stackoverflow
Solution 14 - AngularrepoView Answer on Stackoverflow
Solution 15 - AngularMatjaz HirsmanView Answer on Stackoverflow
Solution 16 - AngularTinh DangView Answer on Stackoverflow
Solution 17 - AngularOphir SternView Answer on Stackoverflow
Solution 18 - AngularsaroraView Answer on Stackoverflow
Solution 19 - AngularLeepiansView Answer on Stackoverflow
Solution 20 - AngularmalemanView Answer on Stackoverflow
Solution 21 - AngularShivang GuptaView Answer on Stackoverflow
Solution 22 - AngularCodieeView Answer on Stackoverflow
Solution 23 - AngularAhmed ElkoussyView Answer on Stackoverflow
Solution 24 - AngularMuhammed OzdoganView Answer on Stackoverflow
Solution 25 - AngularCristian TraìnaView Answer on Stackoverflow
Solution 26 - AngularAhmad Baktash HayeriView Answer on Stackoverflow
Solution 27 - AngularMenelaos KotsollarisView Answer on Stackoverflow
Solution 28 - AngularSimon_WeaverView Answer on Stackoverflow
Solution 29 - AngularlucbonninView Answer on Stackoverflow
Solution 30 - AngularVic SeedoubleyewView Answer on Stackoverflow
Solution 31 - AngularlolcatzftwView Answer on Stackoverflow
Solution 32 - AngularAmirHossein RezaeiView Answer on Stackoverflow
Solution 33 - AngularЕвгений БондаренкоView Answer on Stackoverflow
Solution 34 - AngularAkosthaView Answer on Stackoverflow
Solution 35 - AngularmarekozwView Answer on Stackoverflow
Solution 36 - AngularzurfyxView Answer on Stackoverflow
Solution 37 - AngularishuView Answer on Stackoverflow
Solution 38 - AngularB JarmainView Answer on Stackoverflow
Solution 39 - AngularfwipView Answer on Stackoverflow
Solution 40 - AngularHallmanacView Answer on Stackoverflow
Solution 41 - AngularMaxime LafarieView Answer on Stackoverflow
Solution 42 - AngularRakesh MothukuriView Answer on Stackoverflow
Solution 43 - AngularPatrick WozniakView Answer on Stackoverflow
Solution 44 - AngularMarkosyanArturView Answer on Stackoverflow
Solution 45 - AngularVương Hữu ThiệnView Answer on Stackoverflow
Solution 46 - AngularMike KovetskyView Answer on Stackoverflow
Solution 47 - AngularberslingView Answer on Stackoverflow
Solution 48 - AngularMahmoudView Answer on Stackoverflow