angular2服务方法没有被调用

时间:2016-06-12 15:48:20

标签: angular angular2-services

我尝试创建一个示例angular2服务并使用它,但我不确定我所做的错误。组件无法调用服务方法,请参阅plunker了解更多详细信息https://plnkr.co/edit/tlnGU9Er6GxsOaUMCZZG?p=preview

我的服务代码如下所示

import { Injectable } from 'angular2/core';
import { HTTP_PROVIDERS, Http, Headers, Response, JSONP_PROVIDERS, Jsonp } from 'angular2/http';
import { Configuration } from './Configuration';
import 'rxjs/add/operator/map'
import { Observable } from 'rxjs/Observable';

///Service class to call REST API
@Injectable()
export class SampleService {
    items: Array<any>;

    constructor() {
        this.items = [
            { name: 'Test1' },
            { name: 'Test2' },
            { name: 'Test3' }
        ];
    }

    getItems() {
        return this.items;
    }
}

1 个答案:

答案 0 :(得分:0)

当您引导应用程序(在您的情况下为bootstrap(SampleComponent, [SampleService]))或组件中的providers数组内时,您需要在提供程序数组中包含@Injectable服务。有关依赖注入的更多信息,请参阅此处:https://angular.io/docs/ts/latest/guide/dependency-injection.html

将其添加为提供程序后,无论何时将其注入类构造函数,组件都能够解析它。在您阅读该链接后,依赖注入树将如何工作:)

同样在plunkr中你有两个具有相同选择器的组件(&#39; my-app&#39;)我认为这也是一个错误。

相关问题