angular / angular

Deliver web apps with confidence 🚀
https://angular.dev
MIT License
96.19k stars 25.46k forks source link

Uncaught Error: Can't resolve all parameters for ... #19417

Closed TitaneBoy closed 7 years ago

TitaneBoy commented 7 years ago

I'm submitting a...


[x] Bug report  

Current behavior

Getting an error in the browser console: "Uncaught Error: Can't resolve all parameters for ApiService " Note: ApiService is, I guess, the name of my Service.

Expected behavior

Should inject HttpClient in my service, in developement mode and production mode

Minimal reproduction of the problem with instructions

Hi Guys..I've done a small angular-cli project. I've created 3 services that will get datas. One service is called "FakeService", because it will provide harcoded data...The other service is called "TestService", which has another service (ApiService) injected in its constructor. The ApiService will use HttpClient to get datas from server.

But I got the described error message when I'm using the FakeService (in developement mode)

Here is my app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { environment } from './../environments/environment';

import { AppComponent } from './app.component';
import { ApiService } from './services/api.service';
import { TestService } from './services/test.service';
import { FakeService } from './services/fake.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [
    ApiService,
    {
      provide: TestService,
      useClass: environment.production ? TestService : FakeService
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Here is my api.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

export class ApiService {
  constructor(private httpClient: HttpClient) {

  }
  get(path: string): Array<any> {
    switch (path) {
      case '/tests':
        // this.httpClient.get(`https://localhost/poneyRacerApi/races`)
        //   .subscribe((response: Array<IRaceModel>) => {
        //     return response;
        //   } );
        return [{name: 'London'}, {name: 'Montréal'}];
    }
    return [];
  }
}

Here is my fake.service.ts

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

@Injectable()
export class FakeService {
  constructor() {

  }

  list(): Array<any> {
    return [{name: 'London'}, {name: 'Lyon'}, {name: 'Paris'}, {name: 'Montréal'}];
  }
}

And Finally, here is my test.service.ts

import { Injectable } from '@angular/core';
import { ApiService } from './api.service';

@Injectable()
export class TestService {
  constructor(private apiService: ApiService) {

  }

  list() {
    console.log('Listing races');
    return this.apiService.get('/tests');
  }
}

As you can see in test.service.ts, I inject my other ApiService in the constructor. As you can see in app.module.ts, I'm using TestService when I'm in production (for example, when calling ng serve --prod) and I'm using FakeService when not in production (ng serve)

I have no error message when calling ng serve --prod. But I have the following error message when serving in development mode, aka when using FakeService instead of TestService (ng serve)

Uncaught Error: Can't resolve all parameters for ApiService: (?).
    at syntaxError (compiler.es5.js:1694)
    at CompileMetadataResolver.webpackJsonp.../../../compiler/@angular/compiler.es5.js.CompileMetadataResolver._getDependenciesMetadata (compiler.es5.js:15925)
    at CompileMetadataResolver.webpackJsonp.../../../compiler/@angular/compiler.es5.js.CompileMetadataResolver._getTypeMetadata (compiler.es5.js:15793)
    at CompileMetadataResolver.webpackJsonp.../../../compiler/@angular/compiler.es5.js.CompileMetadataResolver._getInjectableMetadata (compiler.es5.js:15779)
    at CompileMetadataResolver.webpackJsonp.../../../compiler/@angular/compiler.es5.js.CompileMetadataResolver.getProviderMetadata (compiler.es5.js:16070)
    at compiler.es5.js:15999
    at Array.forEach (<anonymous>)
    at CompileMetadataResolver.webpackJsonp.../../../compiler/@angular/compiler.es5.js.CompileMetadataResolver._getProvidersMetadata (compiler.es5.js:15959)
    at CompileMetadataResolver.webpackJsonp.../../../compiler/@angular/compiler.es5.js.CompileMetadataResolver.getNgModuleMetadata (compiler.es5.js:15614)
    at JitCompiler.webpackJsonp.../../../compiler/@angular/compiler.es5.js.JitCompiler._loadModules (compiler.es5.js:26958)

If I remove the constructor's parameter (private httpClient: HttpClient) in my ApiService, I have no error issue when running in developement mode (so when it uses FakeService) but I can't use httpClient to make Http requests.. I've followed the instructions as described in Angular HttpClient doc for the use of HttpClient.

I don't know If it's a true angular issue or if I've done something wrong.. Could you please help me with this issue ?

Thank you very much for your help.

Environment


Angular version:4.4.3

Browser:
- [X] Chrome (desktop) version 60.0.3112.113

For Tooling issues:
- Node version: 8.4.0
- Platform:  Windows

Others:
Visual Studio Code 1.16.1
Angular-Cli: 1.4.3
TitaneBoy commented 7 years ago

Just in case you need to see how looks my app.component.ts

import { Component, OnInit } from '@angular/core';
import { TestService } from './services/test.service';

@Component({
  selector: 'tst-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'tst';
  races: Array<any>;

  constructor(private testService: TestService ) {}

  ngOnInit() {
    this.races = this.testService.list();
  }
}
benelliott commented 7 years ago

You are missing an @Injectable() annotation on your ApiService. Support requests like these should live on StackOverflow not GitHub.

TitaneBoy commented 7 years ago

@benelliott Thank you for the hint. I'm sorry but I thought it was an issue in angular. I've done a lot of research on StackOverflow and on Internet in general, but didn't find a solution.,..So I thought it was an angular issue...Closing it. Thank you and sorry again

amormason commented 6 years ago

Error: Can't resolve all parameters for Router: (?, ?, ?, ?, ?, ?, ?, ?).

I have this error in my angular4 app testing

JavaidAhmad commented 6 years ago

I faced the same issue and resolved in my case, I had missed @Injectable decorator in server.service.ts file

danielvlasceanu commented 6 years ago

I was missing the @ in front of Injectable(). If you get an error in an extremely simple scenario and you find nothing on the web about it, then most probably it's too simple/stupid to be documented. Found that on my own too many times now.

odolha commented 6 years ago

After 1 day on this I realized I had removed some polyfills I didn't think I need. This is what I was missing:

 import 'core-js/es7/reflect';
moequraishi commented 6 years ago

Another scenario for this problem to appear seems to be if you have "ng build --watch" running, and then do "ng build --prod=env" this will cause the DIST files built to be corrupt, and with errors, for my instance it was an error in my data service regarding the @Injectable.

So might want to stop the "ng build --watch" then once it's fully stopped, run "ng build --prod=env".

Just an FYI for those who ran into this issue.

tanou73 commented 6 years ago

After strugling for 1 hour on this, finally, thanks to @odolha , it appears I also had removed core-js/es7/reflect. Adding it again solve the problem !

gabrielalan commented 6 years ago

Thank you very much guys... I just had the same problem: removed the core-js/es7/reflect... so it helped me a lot @odolha, @tanou73

Giwayume commented 6 years ago

Any thoughts on adding actual useful error messages that detect common Angular pitfalls like Vue does?

kabb5 commented 6 years ago

I had this error message also ... what resolved it for me was importing Services from the same Module with relative paths rather than using a barrel.

trotyl commented 6 years ago

@kabb5 That's not something can be helped by Angular, what Angular can get is only an undefined value, there's no way to guess what you did.

jdthorpe commented 6 years ago

I got this error when upgrading an app from angular2 to angular5. In addition to upgrading the CLI and the dependencies and devDependencies in the package.json, I had to update the old /tsconfig.json, and /angular-cli.json, to the new /tsconfig.json, src/tsconfig.app.json, tsconfig.spec.json, and /.angular-cli.json, and then calling

rm -rf node_modules/
npm i 
a2345sooted commented 6 years ago

@odolha this was my issue as well. Glad you spent the day and not me (only took about 20 min to find your post)

The reason I had removed the polyfill was because there is a comment in the polyfill.ts for that polyfill that says this: // Used for reflect-metadata in JIT. If you use AOT (and only Angular decorators), you can remove.

So, I was doing some optimizing for my aot deployment and got rid of it... completely forgetting that local development (using ng-serve) is still using JIT :(

So, thank you sir...

ganeshkbhat commented 6 years ago

Even I faced this issue for a service. For me, adding back ES7/reflect polyfill in polyfill.ts resolved the issue. I had removed them by error.

AlanCrevon commented 6 years ago

For the record, I've just lost a full day on this error... 😭

In main.ts, polyfills MUST ABSOLUTELY be loaded first. Check

import './polyfills.ts';

is your first line.

CajetanRodrigues commented 6 years ago

Okay , so I have finally decoded the error . Note that if there is any unknown import statement in any component , the entire angular app crashes , so make a note of it . I resolved this error after thinking much. Hope it helps Cajetan Rodrigues

m-poh commented 6 years ago

can occur also with circular dependencies (exported helper structures between files).

SerkanSipahi commented 6 years ago

thank you all, i had the same problem: i had removed the core-js/es7/reflect after adding it worked again :)

Ruud-cb commented 6 years ago

I finally found out what was wrong in my case as well. Given the error: Can't resolve all parameters for PageApiService in .../services/pageService.ts: ([object Object], ?)

It looks like it is actually telling me that the place where the question mark is, has an issue. In my case I had HttpClient and a string in the url. In the hope to eventually use it within a provider and provide that string. but it looks like this not not allowed any more?

My service was:

@Injectable()
export class PageApiService<T> {
    private baseUrl: string;

    constructor(private http: HttpClient, private url: string) {
        this.baseUrl = window.location.protocol + '//' + window.location.host + "/api/";
    }

Using inside a module like so:

    providers: [{
        provide: 'ContactPlanPageService', useFactory: http => new PageApiService<ContactPlanModel>(http, 'contactplan/page'),
        deps: [HttpClient]
    }],

It did work though..yet it does give me a warning now that it will be an error in a later version...

dongdongmao commented 6 years ago

i had import core-js/es7/reflect in polyfill.ts but i still have this error. its confuse me a lot.

Uncaught Error: Can't resolve all parameters for ApplicationModule: (?).
    at syntaxError (main.bundle.js:7977)
    at CompileMetadataResolver../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver._getDependenciesMetadata (main.bundle.js:17878)
    at CompileMetadataResolver../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver._getTypeMetadata (main.bundle.js:17771)
    at CompileMetadataResolver../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver.getNgModuleMetadata (main.bundle.js:17639)
    at CompileMetadataResolver../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver.getNgModuleSummary (main.bundle.js:17449)
    at main.bundle.js:17563
    at Array.forEach (<anonymous>)
    at CompileMetadataResolver../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver.getNgModuleMetadata (main.bundle.js:17551)
    at CompileMetadataResolver../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver.getNgModuleSummary (main.bundle.js:17449)
    at main.bundle.js:17536
SerkanSipahi commented 6 years ago

@dongdongmao i had this issue many times when: 1.) forgot to use the @Injectable() in the service and 2.) when some of my angular services, modules, etc exported as export default const foo = 123 instead of export const foo = 123. The key point here is not using default as export.

dongdongmao commented 6 years ago

@SerkanSipahi actually i useing @Injectable() in every service and never use export default in any service or modules....

dongdongmao commented 6 years ago

and if i use ng serve my project can work but if i use webpack-dev-server with my webpack.config, this error Can't resolve all parameters for ApplicationModule: (?). will occur

Tenmak commented 5 years ago

This can also happen when your component extends another one and you forgot to call the super() in your constructor.

jiminikiz commented 5 years ago

This can also happen when your component extends another one and you forgot to call the super() in your constructor.

This was the case for me, extended a class and did not define the constructor at all. Thanks!

Maksym-Vasyukov commented 5 years ago

Happened to me with providing faulty data through the constructor. constructor(private actions$: Actions, private store: MyStore) {} instead of constructor(private actions$: Actions) {}

tomibarbieri commented 5 years ago

The same error occurred to me and I could solve it by rearranging the app.module.ts so that the dependencies are in order of how they are imported. One service imported another that was defined below in the app.module.ts and apparently that was the problem. It was magically solved!

boxmein commented 5 years ago

After 1 day on this I realized I had removed some polyfills I didn't think I need. This is what I was missing:

 import 'core-js/es7/reflect';

We run Angular 2 in a custom Webpack config, without the CLI. After a careful upgrade to Babel 7, we discovered this issue and it got us stumped. A few days later, and the problem is fixed by importing a polyfill 😄

Malex commented 5 years ago

I think the error message should try be more specific on unresolved parameter

leppie commented 5 years ago

I got this as well today, as I forgot to add constructors for a derived class. Was happy with AOT, but not compiling on the fly.

I would have expected the AOT compiler to catch this.

krishnanelloore-gep commented 5 years ago

if you have an index.ts to export your services, check the order of exports. that helped me.

luuuq commented 5 years ago

I'm getting this error in the browsers console: "Can't resolve all parameters for OrdineComponent: (?)." and this on in the Vs code terminal: "WARNING in Circular dependency detected: src\app\ordini\ordini.component.ts -> src\app\shared\ordini.service.ts -> src\app\ordini\ordini.component.ts"

Can anyone help me? I have everything on this repository https://github.com/SDGItalySrl/Burger2Trip

krishnanelloore-gep commented 5 years ago

src\app\ordini\ordini.component.ts -> src\app\shared\ordini.service.ts -> src\app\ordini\ordini.component.t

Its clear that you are trying to inject the ordine service in the ordine component and ordine component in service. That is not possible. to instantiate the component you need the service and to instantiate the service you need the component. Please read about the dependency injection pattern.

JayPerfetto commented 5 years ago

I have run into this trying to inject an interface, thinking it was a class -> make sure your component level variables are declared outside of your constructor injection.

Alexander-Akimov commented 5 years ago

In my case this problem appear only with ng build --prod

and it was in the following code:

import RestDataSource from './rest.datasource'; instead - import {RestDataSource} from './rest.datasource';

maybe it helps some one

PhiLhoSoft commented 5 years ago

It seems this message can have many causes. In my case, it was because I tried to inject service classes from a library, except these classes don't have an @Injectable() annotation because they are intended to be extended (even if not adding any behavior) and are not abstract either.

AlexandruCalinica commented 5 years ago

In my case I was simply injecting in the constructor the Router service without using it. After deleting this, everything works fine.

xxxKimihiro commented 5 years ago

在我的情况下,这个问题只出现 ng build --prod

它在以下代码中:

import RestDataSource from './rest.datasource'; 相反 - import {RestDataSource} from './rest.datasource';

也许它可以帮助一些人

Hahaha.I also encountered this situation.

philly-vanilly commented 5 years ago

This error might also occur when you have circular dependencies (for example because you use barrel imports in a wrong way).

This might be especially confusing because the dependency injection will work in other classes but not in the one that has a circular dependency.

s-ghasemi31 commented 5 years ago

Problem was solved by adding Inject directive to Service in Component constructor(@Inject(AppService) service: AppService)

jonfasking commented 5 years ago

I had a slightly different problem so I'll drop it here in case anyone else runs across it.

I had recently spun up an v8 project, and ran into the high memory issues when compiling for prod https://github.com/angular/angular-cli/issues/13734. Could not figure out a solution I was happy with so reverted back to v7. The projects generated for v8 have a different transpile targets in the tsconfig and therefore the decoration of modules is different. Anyway in my case I needed to use the targets/modules values from a V7 project.

TL;DR: If you reverted from an NG8 project back to NG7. Use this NG7 tsconfig.json:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "es2015",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ]
  }
}
alansferreira commented 5 years ago

In my case the problem has already occurred when a component file exports more than one object type for example:

'my-test.component.ts

export enum MyTestEnum {      ... }

@Component (...) expose class MyTestComponent {      ... }

labidiaymen commented 5 years ago

For me, I was exporting as a default.

image

angular-automatic-lock-bot[bot] commented 5 years ago

This issue has been automatically locked due to inactivity. Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

This action has been performed automatically by a bot.