我不能为我的生命得到一个简单的服务注入到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