简体   繁体   English

angular2服务方法没有被调用

[英]angular2 service method not getting invoked

I tried to create a sample angular2 service and consume it, but I am not sure about the mistake that i have done. 我试图创建一个示例angular2服务并使用它,但我不确定我所做的错误。 the service method couldn't be called by the component, Please see the plunker for more details https://plnkr.co/edit/tlnGU9Er6GxsOaUMCZZG?p=preview 组件无法调用服务方法,请参阅plunker了解更多详情https://plnkr.co/edit/tlnGU9Er6GxsOaUMCZZG?p=preview

My service code looks like below 我的服务代码如下所示

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

You need to include the @Injectable service in the array of providers when you bootstrap the app (in your case bootstrap(SampleComponent, [SampleService]) ) or inside the providers array in the component. 当您引导应用程序(在您的情况下为bootstrap(SampleComponent, [SampleService]) )或组件中的providers数组内时,您需要在提供程序数组中包含@Injectable服务。 More on Dependency injection you can read here: https://angular.io/docs/ts/latest/guide/dependency-injection.html . 有关依赖注入的更多信息,请参阅此处: https//angular.io/docs/ts/latest/guide/dependency-injection.html

After you add it as a provider, whenever you inject it in the class constructor, the component will be able to resolve it. 将它作为提供程序添加后,无论何时将其注入类构造函数,组件都能够解析它。 It will be clear how the tree of dependency injection works after you read that link :) 在您阅读该链接后,依赖注入树将如何工作将很清楚:)

Also in the plunkr you have two components with the same selector ('my-app') which I guess is also a mistake. 同样在plunkr你有两个组件与相同的选择器('我的应用程序'),我想这也是一个错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM