506

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.

Liam
  • 27,717
  • 28
  • 128
  • 190
Keith Otto
  • 5,118
  • 2
  • 11
  • 7
  • 16
    Maybe the import? Is `'../'` an `index.ts` (Barrel)? Can you try to import it from the file where it is declared directly instead? – Günter Zöchbauer Jun 23 '16 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. – Keith Otto Jun 23 '16 at 18:04
  • 17
    Generally a circular dependency. – Gary Jul 13 '17 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 – Enn Nov 20 '17 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. – Rammgarot Aug 28 '18 at 15:37
  • In my case I was using a default export, it worked when I changed to a named export. – Jacob Ensor Aug 14 '19 at 13:53
  • in my case issue was I am trying to inject interface into constructor. – Paritosh Mahale Oct 31 '19 at 07:19
  • For me it was the ordering of the imports. Once I put the import for the service/component before all other dependant components/services it worked. – ComeIn Nov 02 '20 at 06:48

49 Answers49

484

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)

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 19
    this is correct if you have for example a service injected into another service that first one needs to come first in the barrel. – Joao Garin Aug 30 '16 at 14:52
  • 19
    The Angular2 team doesn't recommend barrels anymore because of a lot of such issues. Glad to hear I could help :) – Günter Zöchbauer Sep 14 '16 at 08:54
  • 13
    Didn't know that Angular 2 team doesn't recommend barrels. If so, they should note that in the [glossary](https://angular.io/docs/ts/latest/guide/glossary.html) that discusses their benefit. And projects like [angular2-webpack-starter](https://github.com/AngularClass/angular2-webpack-starter) should not use them. – Blue Sep 26 '16 at 14:36
  • 1
    It's not that they say you should not use them but they had a distinct doc topic about barrels but they removed it because they don't want to explicitly recommend it because it too often causes issues. They also had it in the style guide where they also removed it. So it's not discouraged but also not recommended. I guess with the introduced `NgModel` they are less relevant anyway. – Günter Zöchbauer Sep 26 '16 at 14:40
  • 3
    It seams this was fixed (not an issue in `2.0.2`). I find barrels still useful, specially when I need to import several models and services between different modules. This `import { cleanValues, getState, FirebaseService, NotificationService, ... } from '../../shared/services';` was a pain when it didn't work (; `NgModule` is no help with singleton services... – Sasxa Oct 11 '16 at 07:13
  • You are right about singleton service. You still need to import them when you inject them. Barrels are not discouraged at all. The Angular2 team just didn't recommend them anymore. – Günter Zöchbauer Oct 11 '16 at 07:18
  • I replaced all (not 100% sure) related barrel imports but still had the error. `forwardRef` solution did help. Can you please include it in your answer for visibility? http://stackoverflow.com/a/41093099/723891 – Igonato Dec 22 '16 at 11:02
  • Interesting. Thanks for the feedback. To me it seems this has become quite seldom but there seem to be some situations where it's till necessary. I'm only aware that it is required if a class in the same file further down is referenced. – Günter Zöchbauer Dec 22 '16 at 11:05
  • 1
    First off, thanks for this answer. Save me some time. Second, in my experience, barrels have been quite safe to use (until I ended up with this problem, of course). But, in retrospect, I did notice that the problem occurs only when you `import from` `'./'`, `'./..'`, etc. like locations (no other actual folder names in the 'from location'). Just FYI. – Krishnan Jan 28 '17 at 17:53
  • 1
    @Sasxa, I still have this problem in Angular v4.3.6 and replacing the reference to the actual file solves the problem. If it had been fixed in v2.0.2, does it mean it was re-introduced in v4.x? – Alex Klaus Oct 05 '17 at 04:13
  • 1
    @AlexKlaus I think this is a TypeScript issue, not an Angular issue. – Günter Zöchbauer Oct 05 '17 at 04:16
  • 5
    Argghh I solved it by changing the order of the exports in the barrel (index.ts) file.. thank you so much – Spock Jan 30 '18 at 14:30
  • 2
    I wrote a small article about this issue, just in case anyone finds it useful: https://medium.com/@dSebastien/avoiding-import-issues-in-typescript-monorepos-d5a4b21f90ef – dSebastien Apr 18 '20 at 12:35
373

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.

J.P.
  • 5,567
  • 3
  • 25
  • 39
  • Yeah this error is typically because you have forgot to add @Injectable and for instance you may just be importing the `Router` from '@angular/router' and without that injectable, this error will always happen (as soon as you decide to make one line of code use that injected router. – Eric Bishard Oct 11 '17 at 20:35
  • Awesome answer, my issue was that I added a method in my service and didn't add a semi colon after the final brace. I have no idea why it has to be this way yet it's not the case in component classes... for now am only glad to move on! – egimaben Oct 27 '17 at 11:03
  • I had a simple model that gave me this error. I used the shortcut where you create your properties in the constructor of the model. The types of the properties was only string and int. Then suddenly this issue started occurring. Adding @Injectable() fixed the issue. Weird because none of my other models has Injectable added. I have to add that I upgraded quite a few libraries before adding this new model. Possibly had something to do with it, but working now. Thanks. – Moutono May 15 '18 at 18:03
  • @Moutono Correct. With an empty constructor in your service, the dependency injection doesn't seem to get triggered and `@injectable()` isn't required. Which is another oddity on itself. For good measure I'd still add it though, simply for when you should ever decide to inject something. – J.P. May 21 '18 at 16:10
  • Bear in mind that if your service has a base class that too needs to be decorated with @Injectable() – Sam Shiles Nov 15 '18 at 06:55
  • Also applies to abstract base classes in the hierarchy - even though the cannot be instantiated, they need `@Injectable()` – theMayer Dec 12 '18 at 20:26
  • Yep, that was my problem as well. I did add a decorator, but then added a helper class and inserted it between the service class and the decorator. No compilation errors, no warnings. Until this one. – Ya. Jul 16 '19 at 05:50
  • It did the job. I created an error interceptor but it won't work untill I add injectable. Awesome. – Inderjeet Singh Dec 10 '19 at 04:52
  • Perfect! Did the job! – Marek Jan 14 '21 at 21:00
121

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

Zabavsky
  • 13,340
  • 8
  • 54
  • 79
Reactgular
  • 52,335
  • 19
  • 158
  • 208
  • 3
    `forwardRef()` was there already in alpha ;-) It's only needed if `Mobile` service is declared further down in the same file. If the classes are in different files, there is no need for `forwardRef()` – Günter Zöchbauer Dec 12 '16 at 06:27
  • 4
    Günter Zöchbauer, I am still trying to figure out the real problem with my code, but in the meantime `forwardRef()` did help to get rid of the `Can't resolve all parameters for ...` message. At least the component is working while I'm looking for a nicer solution to the problem. (And yes, the failing dependency is imported directly from its file) – Myk Dec 12 '16 at 10:40
  • 4
    @GünterZöchbauer I've updated my answer with references. I'm not trying to take away from your answer, but this actually solves the problem and people need to know about it. If you google the question there are no results that say to use `forwardRef`. It's very hard to find. Took me all day yesterday to resolve this problem. – Reactgular Dec 12 '16 at 14:26
  • Weird. I posted at least a dozen answers that suggest using `foreardRef` myself but not anymore after `NgModule` was introduced. I'm not worried about loosing reps. I'm just curious why you run into this after this didn't pop up anymore since a few months. I'll have a closer look when I'm back home in a few days. Thanks a lot for the feedback. – Günter Zöchbauer Dec 12 '16 at 20:26
  • 2
    If someone also got lost about the imports: import { Component, Inject, ForwardRefFn, forwardRef } from '@angular/core'; – Natanael Jan 06 '17 at 16:53
  • Using Ionic3 to include services within other services, this is the only solution I've managed to get to work! – ganey Jul 25 '17 at 23:39
  • It's a weird error message. Doesn't even give you what you can't inject. So went thru adding all constructor args to service, except for Events. Then trial and error commenting out the forward ref decorators until I pinpointed the culprit. Most unhelpful! – JGFMK Aug 20 '17 at 11:06
  • @JGFMK it is a bad error, and there are variants of the same problem but with different error messages. I once had to use `forwardRef` with `@ContentChildren()` but it took me many hours to figure out that was what the fix was. – Reactgular Aug 20 '17 at 15:57
84

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 { ... }
KANJICODER
  • 3,611
  • 30
  • 17
28

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

Community
  • 1
  • 1
Michael
  • 5,994
  • 7
  • 44
  • 56
25

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.
Stephen Paul
  • 37,253
  • 15
  • 92
  • 74
  • 1
    This is definitely what happened to me, and this is the way to go. If you know you have more than one service requiring updates, use an EventService. It's more extensible as you'll no doubt have to tap into those events as you extend the application based on these events. – themightybun Jan 12 '17 at 16:53
20

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{
}
JsAndDotNet
  • 16,260
  • 18
  • 100
  • 123
  • 2
    In my case, I'd added extra classes and interfaces between @Injectable and the service class definition, so the service class was no longer marked as injectable. – Herc Apr 25 '17 at 16:30
  • If you completely forget the @Injectable() decorator on a service class that consumes other injectable services, then your improperly decorated service will also throw this error. – I. Buchan Nov 01 '17 at 21:15
15

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

{
  "compilerOptions": {

     ...

    "emitDecoratorMetadata": true,

     ...

    }

}
Stewart_R
  • 13,764
  • 11
  • 60
  • 106
15

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

AJ Richardson
  • 6,610
  • 1
  • 49
  • 59
  • 1
    This is now 'core-js/features/reflect'. Also, the polyfill is only needed in JIT (dev) mode, so it can be conditionally loaded using dynamic imports and 'magic comments' in webpack. For example: if (process.env.NODE_ENV !== 'production') { import(/* webpackMode: "eager" */ 'core-js/features/reflect').then(() => {});}. See https://webpack.js.org/api/module-methods/#magic-comments. – Stevethemacguy Dec 04 '20 at 01:38
14

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 {
.....
}
Tomasz
  • 4,847
  • 2
  • 32
  • 41
Bart
  • 273
  • 3
  • 8
10

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.

M K
  • 9,138
  • 7
  • 43
  • 44
  • I've also had it when there's a dependency on a function simply defined in the same file. Splitting it into a separate file fixed it. – Joe Jun 01 '17 at 11:09
  • 1
    Thank you for mentioning it. I've found myself in the exact situation. I didn't realized that accessing static classes directly can have something to do with the DI. I had this scheme: `A -> B` and both of them were using the same static class. The solution with `forwardRef` helps, but I'm going to look how this could be untangled. I will probably try to make a real service out of this static class (this will lead to a better design as well). – Slava Fomin II Jun 29 '17 at 09:00
10

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) {}
Alf Moh
  • 7,159
  • 5
  • 41
  • 50
8

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 { ... }
otiai10
  • 4,289
  • 5
  • 38
  • 50
7

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

repo
  • 748
  • 1
  • 8
  • 19
6

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

Matjaz Hirsman
  • 326
  • 3
  • 9
6

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

Tinh Dang
  • 448
  • 4
  • 11
5

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.

sarora
  • 913
  • 9
  • 20
4

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

Ophir Stern
  • 1,277
  • 12
  • 22
  • 2
    I was just missing an `@Inject` annotation. I was overlooking exactly what the error message says a bit. If you don't suspect circular dependencies, just go to the class mentioned in the error and look at all the constructor parameters and any class members annotated with `@Inject` and make sure you're doing DI right on all of them. More on DI here: https://angular.io/docs/ts/latest/guide/dependency-injection.html – Alexander Taylor Jan 30 '17 at 23:13
3

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.

maleman
  • 98
  • 1
  • 9
3

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]
})
Shivang Gupta
  • 3,139
  • 1
  • 25
  • 24
3

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.

Satendra
  • 6,755
  • 4
  • 26
  • 46
Codiee
  • 3,047
  • 2
  • 17
  • 18
3

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';
Ahmed Elkoussy
  • 8,162
  • 10
  • 60
  • 85
3

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.

Muhammed Ozdogan
  • 5,341
  • 8
  • 32
  • 53
  • This worked for me, but I have no idea why. Do both the service and the component which receives it through DI need to be providedIn: root in order for DI to work? – Mike Furlender Jul 25 '19 at 15:23
3

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

Not good :(

lucbonnin
  • 235
  • 2
  • 9
  • Same here. Not the most intuitive error for circular dependencies, but at least it fails on buildtime rather than runtime – TabsNotSpaces Oct 14 '22 at 16:49
3

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

3

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]

lolcatzftw
  • 556
  • 3
  • 16
3

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 {
ASANIAN
  • 372
  • 2
  • 8
2

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) {}
}
Community
  • 1
  • 1
Ahmad Baktash Hayeri
  • 5,802
  • 4
  • 30
  • 43
2

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.

Menelaos Kotsollaris
  • 5,776
  • 9
  • 54
  • 68
2

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.

Simon_Weaver
  • 140,023
  • 84
  • 646
  • 689
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.

Vic Seedoubleyew
  • 9,888
  • 6
  • 55
  • 76
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.

AmirHossein Rezaei
  • 1,086
  • 1
  • 16
  • 20
1

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

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

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

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

Akostha
  • 679
  • 7
  • 8
0

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

marekozw
  • 356
  • 2
  • 7
0

It happens when referring an interface as well.

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

zurfyx
  • 31,043
  • 20
  • 111
  • 145
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

ishu
  • 1
  • 2
0

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

 ng serve -aot
DGmip
  • 193
  • 2
  • 9
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.

fwip
  • 395
  • 3
  • 6
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.

Hallmanac
  • 529
  • 2
  • 8
  • 14
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)

Maxime Lafarie
  • 2,172
  • 1
  • 22
  • 41
0

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

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$);
  }
  // ...
}
Patrick Wozniak
  • 1,492
  • 1
  • 13
  • 16
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

MarkosyanArtur
  • 1,359
  • 13
  • 10
0

You can try running the following command again:

ng serve --open

Vương Hữu Thiện
  • 1,460
  • 14
  • 21
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.

Mike Kovetsky
  • 1,638
  • 1
  • 14
  • 24
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
  ) {}
bersling
  • 17,851
  • 9
  • 60
  • 74
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';
Mahmoud
  • 456
  • 3
  • 13
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.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
itty
  • 55
  • 6