无法将简单的服务注入组件

时间:2016-09-16 16:13:03

标签: angularjs angular typescript

我无法为我的生活获得一个简单的服务来注入Angular2组件。一切都在转变,但我一直在努力:

EXCEPTION: TypeError: Cannot read property 'getSurveyItem' of undefined

当我检查我的组件的构造函数时,该服务是未定义的,因此我花了整整一天的时间才真正陷入困境。这里有一些类似的问题,但我已经做了那些建议,所以我相信我错过了别的东西。我对此很新,但看起来我所做的非常基本。

我的服务项目“模型”

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); 

我相信有人会告诉我这是非常明显的事情,但我真的看不出我错过了什么。

1 个答案:

答案 0 :(得分: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

相关问题