515

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.

8
  • 17
    Maybe the import? Is '../' an index.ts (Barrel)? Can you try to import it from the file where it is declared directly instead? Commented Jun 23, 2016 at 17:11
  • Miraculously that seems to have fixed it! Odd that it wouldn't work using the barrel when the other components I tested the service with did. If you want to post that as an answer instead of comment I'll accept it. Commented Jun 23, 2016 at 18:04
  • 17
    Generally a circular dependency. Commented Jul 13, 2017 at 17:26
  • I've had this issue with circular dependency as well. Its worth noting that newer versions of web pack are much better at telling you this Commented Nov 20, 2017 at 14:56
  • Looks like circular dependency, If you use angular >=4 so you can get rid of intex.ts (barrel) and import all you need directly. Commented Aug 28, 2018 at 15:37

49 Answers 49

1
2
1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

This was my case. I accidentally imported from the index.ts file, instead from the actual path.
1

import {Injector} from '@angular/core'; import {ServiceA} from './service-a'; @Component({ // ... }) class MyComp { constructor(private injector: Injector) { const serviceA = injector.get(ServiceA); } }

Comments

1

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

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

Comments

0

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

Comments

0

It happens when referring an interface as well.

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

Comments

0

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

Comments

0

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

 ng serve -aot 

Comments

0

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.

Comments

0

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.

Comments

0

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)

Comments

0

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

Comments

0

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

Comments

0

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

Comments

0

You can try running the following command again:

ng serve --open

Comments

0

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.

Comments

0

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

Comments

0

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

Comments

0

I tried almost all the answers given here but none of them helped me.

What worked for me was closing the project in Visual Studio Code, opening the file explorer, entering my project and deleting the dist folder.

Then I did every build to all the libs and then re-ran the project in npm start.

Comments

1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.