Search code examples
angulartypescriptdependency-injectionangular-services

Can't resolve all parameters for component when service is injected


I have a problem when i am injecting service into my component. The service is provided globaly. I get this error in my code editor.

Can't resolve all parameters for SomeComponent in some.component.ts: (?). ng(0)

The strange thing is that my app works and compiler doesn't throw any errors.

Service

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

@Injectable({
  providedIn: 'root',
})
export default class AppService {
  constructor(private _http: HttpClient) {}

  someMethod() {}
}

Component

import { Component } from "@angular/core";
import AppService from "./app.service";

@Component({
  selector: "app-some-component"
})
export class SomeComponent {
  constructor(private _appService: AppService) {}
}

I was looking through answers here and couldn't get to any that provides answer. Some answers gave solution to change order of constructor injections.


Solution

  • After a number of tries, i figured that i made a mistake of export default class AppService.

    I found out that it is not recommended to use default exports in Angular because AOT wont work. Here is the article that covers that problem: Why isn't "export default" recommended in Angular?

    So solution is to always export normally a class:

    Service

    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    
    @Injectable({
      providedIn: 'root',
    })
    export class AppService {
      constructor(private _http: HttpClient) {}
    
      someMethod() {}
    }
    

    Component

    import { Component } from "@angular/core";
    import { AppService } from "./app.service";
    
    @Component({
      selector: "app-some-component"
    })
    export class SomeComponent {
      constructor(private _appService: AppService) {}
    }
    

    Hope this helps someone not lose hours like me.