2016-09-16 61 views
0

我不能爲我的生命得到一個簡單的服務注入到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); 

我相信有人會告訴我,這是一件很明顯的,但我實在看不出有什麼我已經錯過了。

+0

u的注入,這樣你們不需要這樣'提供商:[SurveyItemService] '請在控制檯上檢查錯誤。 –

+0

我已經有或沒有該行的代碼(我沒有它,但看到它的角度文檔,所以把它)。無論哪種方式,我的服務仍未定義,並沒有被注入。 – Modika

+0

如果服務沒有被注入,那麼也應該有注入錯誤。這可能是emitDecoratorMetadata的一個問題,你是否試圖用@Inject顯式注入它?見http://stackoverflow.com/questions/30311514/injectables-in-angular2 – estus

回答

0

我剛纔跟RC7版本和它沒有任何錯誤的工作進行了測試。當你正在使用舊版本嘗試按照以下建議,

引導

import {bootstrap} from 'angular2/platform/browser'; 
import {SurveyItemComponent} from './app.component'; 
import {SurveyItemService} from './services/survey-item.service'; 

bootstrap(SurveyItemComponent,[SurveyItemService]); 

我的組件

@Component({ 
    selector: 'survey-item', 
    template: '<div><h1>{{pageTitle}}</h1></div>', 
    // providers: [SurveyItemService] <----commenting it 
}) 

如果你需要一個參考,下面鏈接在最新版本及其工作。在此發佈工作鏈接。它可能會或可能不會幫助你。

檢查瀏覽器的控制檯。

https://plnkr.co/edit/FDY4CBAPcaxxlH32ADQp?p=preview

+1

是的,我用的是舊版本升級,但並沒有解決它,因爲它似乎在我正在使用舊版本和視覺2013似乎並不符合打字稿如此之大(我相信它的設置,但無法找到它)。我升級並將項目轉移到Visual Studio代碼,它現在可以工作,我只需要弄清楚如何在我的遺留應用程序(WebForms bleaghhh)之後進行集成。 – Modika