如何从角度2的服务中获取数据?

时间:2016-02-11 06:43:05

标签: typescript angular

我能够使用http(在同一个组件中)获取数据。但是我没有使用service.can获取数据我们从服务器调用服务方法和grt数据并在组件上显示? 我尝试提供服务并尝试从服务器获取数据。但我不知道如何使用此服务? http://plnkr.co/edit/hfhY6EdLVNOLP6d4QsWP?p=preview

import {Component, Injectable,Input,Output,EventEmitter} from 'angular2/core'
import {Http, HTTP_PROVIDERS} from 'angular2/http';
import 'rxjs/add/operator/map';
// Name Service
export interface myData {
   name:Array;
}



@Injectable()
export class SharedService {
  sharingData: myData=[{name:"nyks"}];
   constructor(private http:Http) {
    }
  getData:Array()
  {
    this.sharingData.name=this.http.get('data.json')
        .map(res => res.json());

    return this.sharingData.name;
  }
} 

2 个答案:

答案 0 :(得分:3)

你可以试试这个:

import {SharedService} from './service';

@Component({
  (...)
  providers: [SharedService]
})
export class MyComponent {
  constructor(private service:SharedService) {
    this.service.getData();
  }
}

也就是说,我看到你的服务有些奇怪,因为Angular2 HTTP支持利用了observables(异步处理)。我会这样重构:

@Injectable()
export class SharedService {
  //sharingData: myData=[{name:"nyks"}];
  constructor(private http:Http) {
  }

  getData:Array() {
    return this.http.get('data.json')
               .map(res => res.json());
  }
}

并在组件中:

import {SharedService} from './service';

@Component({
  (...)
  template: `
    <ul>
      <li *ngFor="d of dataToDisplay">{{d.name}}</li>
    <ul>
  `,
  providers: [SharedService]
})
export class MyComponent {
  constructor(private service:SharedService) {
    this.service.getData().subscribe(data => {
      this.dataToDisplay = data;
    });
  }
}

这个答案可以为您提供更多详细信息:

答案 1 :(得分:0)

您需要将SharedService添加到bootstrap

中的提供程序列表中
bootstrap(MainComponent,[
  ROUTER_PROVIDERS,
  provide(LocationStrategy, {useClass: HashLocationStrategy}),
  HTTP_PROVIDERS,
  SharedService
]);

然后你可以将它注入你的组件

export class MainComponent {
    constructor(private sharedService:SharedService) {}

    clickHandler() {
      this.data = sharedService.getData()
    }
}

需要修复getData方法

 {
    this.sharingData.name=this.http.get('data.json')
        .map(res => res.json());
    // the following line is executed before the result arrives
    // because above code is async
    // therefore this always returns null
    return this.sharingData.name;
  }
相关问题