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

前端 未结 30 1617
无人共我
无人共我 2020-11-22 17:18

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 o

相关标签:
30条回答
  • 2020-11-22 17:29

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

    0 讨论(0)
  • 2020-11-22 17:29

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

    Not good :(

    0 讨论(0)
  • 2020-11-22 17:29

    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.

    0 讨论(0)
  • 2020-11-22 17:30

    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.

    0 讨论(0)
  • 2020-11-22 17:30

    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

    0 讨论(0)
  • 2020-11-22 17:31

    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.

    0 讨论(0)
提交回复
热议问题