简体   繁体   中英

Why can't Angular2 inject my service?

I was in the process of writing a plnkr to test some routing issues when suddenly this error message popped up and wouldn't go away no matter what I changed in my code:

EXCEPTION: Error: Uncaught (in promise): Can't resolve all parameters for EmployeeListComponent: (?).

Here's the relevant portion of the code:

export class EmployeeListComponent {
  employees: Employee[];
  constructor(private _employeeService: EmployeeService) {
    _employeeService.getAll().subscribe(employees =>
      this.employees = employees);
  }
}

So it seems Angular is unable to resolve EmployeeService , right? I commented it out in the above snippet and sure enough, no errors.

Did I forget to register it within main.ts or app.component.ts ? Nope,

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

import { 
    ROUTER_DIRECTIVES
} from '@angular/router';

import {
  EmployeeService
} from './employee.service';


@Component({
  selector: 'plk-app',
  template: '<router-outlet></router-outlet>',
  directives: [ 
    ROUTER_DIRECTIVES
  ],
  providers: [
    EmployeeService
  ]
})
export class AppComponent {

}

Should I have registered it in main.ts ? Well, I had when that error first cropped up and I then moved it to app.component.ts to check if that would fix it, it didn't.

At the moment I can't see the forest for the trees and Angular's error messages aren't really helping (they never have been). Is there anyone here who can spot the issue? The plnkr can be found here .

After visiting on few questions I came to know that this problem occurs because of absence of TypeScript compiler. If you are not using typescript compiler then you need to explicitly inject service by using ' Inject ' from ' @angular/core '. I have tried it in plunker provide by you and its working.

In your case you need to make changes in your employee-list.component.ts . Import Inject from @angular/core and in constructor explicitly inject your service like:

constructor(@Inject(EmployeeService) private employeeService: EmployeeService){}

Feel free for any question and accept my answer if you found the solution helpful to you.

Here is working plunker

First step:

system.js.config

var config = {
    // DEMO ONLY! REAL CODE SHOULD NOT TRANSPILE IN THE BROWSER
    transpiler: 'ts',
    typescriptOptions: {
      tsconfig: true,
      emitDecoratorMetadata: true <== add this line
    },

Second step:

employee.model.ts now looks like:

export class Employee {
  id: number;
  name: string;
}

Third step:

Remove async pipe from template of EmployeeListComponent . It should be:

<li *ngFor="let employee of employees">
  ...
</li>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM