我不能爲我的生命得到一個簡單的服務注入到Angular2成分簡單的服務。一切都transpiling,但我只是不斷收到:無法獲得注入部件
EXCEPTION: TypeError: Cannot read property 'getSurveyItem' of undefined
當我在我的組件的構造檢查,該服務是不確定的,所以我在這度過了整整一天後,真正卡住。這裏有一些類似的問題,但我已經在做這些建議,所以我確信我錯過了其他的東西。我對此很新,但看起來我所做的是非常基本的。
我ServiceItem 「模型」
export class SurveyItem {
constructor(public id: number, public imageUrl: string) {}
}
我的服務(ServiceItemService)
import { Injectable } from 'angular2/core';
import { SurveyItem } from '../models/survey-item.model';
@Injectable()
export class SurveyItemService{
getSurveyItem(): SurveyItem {
return { id: 23, imageUrl: '/secure/files/189008d0-5a8e-4e69-927c-0fdfa6f7ea7a.jpg'}
}
}
我的組件
import {Component, OnInit, Injectable } from 'angular2/core';
import {SurveyItem} from './model/survey-item.model';
import {SurveyItemService} from './services/survey-item.service';
@Component({
selector: 'survey-item',
template: '<div><h1>{{pageTitle}}</h1></div>',
providers: [SurveyItemService]
})
export class SurveyItemComponent implements OnInit {
pageTitle: string = 'Survey Item';
surveyItem: SurveyItem;
constructor(private surveyItemService: SurveyItemService) {
console.log(surveyItemService);
}
getSurveyItem(id: any): void {
this.surveyItem = this.surveyItemService.getSurveyItem();
}
ngOnInit(): void {
this.getSurveyItem(23);
}
}
引導
import {bootstrap} from 'angular2/platform/browser';
import {SurveyItemComponent} from './app.component';
bootstrap(SurveyItemComponent);
我相信有人會告訴我,這是一件很明顯的,但我實在看不出有什麼我已經錯過了。
u的注入,這樣你們不需要這樣'提供商:[SurveyItemService] '請在控制檯上檢查錯誤。 –
我已經有或沒有該行的代碼(我沒有它,但看到它的角度文檔,所以把它)。無論哪種方式,我的服務仍未定義,並沒有被注入。 – Modika
如果服務沒有被注入,那麼也應該有注入錯誤。這可能是emitDecoratorMetadata的一個問題,你是否試圖用@Inject顯式注入它?見http://stackoverflow.com/questions/30311514/injectables-in-angular2 – estus