2016-06-12 122 views
0

我试图创建一个样本angular2服务并使用它,但我不确定我所做的错误。服务方法不能由组件调用,请参阅plunker更多细节https://plnkr.co/edit/tlnGU9Er6GxsOaUMCZZG?p=previewangular2服务方法没有被调用

我的服务代码看起来像下面

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

使用新的 - >角度 - > 2.0 TS http://take.ms/AJTLh – yurzui

+0

你是index.html页面不包括任何anuglar2代码,它不会被设置为从typescript转换到javascript使用System.js。请考虑以下教程以完成缺少的peices:https://angular.io/docs/ts/latest/quickstart.html – Tucker

+0

请注意,您的组件文件名是'SampleCompoent.ts' –

回答

0

您需要包括供应商的阵列中的@Injectable服务当你引导应用程序(在你的案例bootstrap(SampleComponent, [SampleService]))或组件内的提供者数组。更多关于依赖注入,你可以在这里阅读:https://angular.io/docs/ts/latest/guide/dependency-injection.html

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

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

+0

我完成了所有您提出的更改,仍然没有按预期工作。请您检查重新搜索并纠正我的错误? – Krishnan

+0

https://plnkr.co/edit/hI7z0Hnx7ssgDdwd3n12?p=preview在这里,你去..我叉并更新它..你有2个问题。第一个是在bootstrap.ts中,在将它用于来自'。/ SampleService''''的依赖数组'''import {SampleService}之前,您没有导入该服务。其次,你从错误的地方导入了bootstrap函数本身(你没有在那里使用RC版本,而是一个测试版本),它是从'angular2/platform/browser'导入{bootstrap};''不是''' '@angular/...'''。第三个单词'''ng'在ngFor中不存在,所以我用#item改变了它 –