簡體   English   中英

為什么Angular2不能注入我的服務?

[英]Why can't Angular2 inject my service?

我正在編寫一個plnkr來測試一些路由問題突然出現這個錯誤消息,無論我在代碼中改變了什么都不會消失:

EXCEPTION:錯誤:未捕獲(在承諾中):無法解析EmployeeListComponent的所有參數:(?)。

這是代碼的相關部分:

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

所以似乎Angular無法解析EmployeeService ,對吧? 我在上面的片段中對此進行了評論,當然,沒有錯誤。

我忘了在main.tsapp.component.ts注冊嗎? 不,

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 {

}

我應該在main.ts注冊嗎? 好吧,我在第一次出現錯誤時就把它移到了app.component.ts來檢查是否會修復它,但事實並非如此。

目前我無法看到森林中的樹木,而Angular的錯誤消息並沒有真正幫助(它們從來沒有)。 這里有人能發現這個問題嗎? plnkr可以在這里找到。

在訪問幾個問題后,我發現由於缺少TypeScript編譯器而出現此問題。 如果您沒有使用typescript編譯器,那么您需要使用' @angular/core '中的' Inject '來顯式注入服務。 我已經嘗試過你提供的plunker及其工作。

在您的情況下,您需要在employee-list.component.ts進行更改。 @angular/core導入Inject並在構造函數中顯式注入您的服務,如:

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

如果您發現該解決方案對您有幫助,請隨意提出任何問題並接受我的回答。

這是工作的plunker

第一步:

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
    },

第二步:

employee.model.ts現在看起來像:

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

第三步:

EmployeeListComponent模板中刪除async管道。 它應該是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM