angular2 服务方法未被调用

angular2 service method not getting invoked

我试图创建一个示例 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;
    }
}

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

将其添加为提供程序后,无论何时将其注入 class 构造函数,组件都可以解析它。阅读 link :)

之后,依赖注入树是如何工作的就会很清楚了

另外,在 plunkr 中,您有两个组件具有相同的选择器 ('my-app'),我猜这也是一个错误。