在Angular2中调用服务

时间:2016-04-07 11:12:33

标签: angular

我刚开始学习angular2.I在angular2中调用服务时遇到问题。服务调用成功,但我有问题如何处理数据。在Angular1我们确实喜欢这样:

DemoService.getExchangeDataConnection().then(function(response){
//here we handle all the data
})

Angular2

constructor(private _sampleService: SampleService){
    this._sampleService = _sampleService;
}


 onClickMe(){
    this.clickMessage ='You are my hero!';
     this.error = "";
    this.countries = [];
    this._sampleService.test()
     .subscribe(
        data => this.countries = data,
        error => this.error = "Region " + this.region + " is invalid."
     );

  }

这里我该如何处理数据? 这是我的服务:

export class SampleService {

constructor(http: Http){
       this.http = http;
   }

   test(){
console.log(AppSettings.API_ENDPOINT);
    return this.http.get(AppSettings.API_ENDPOINT+"oceania").toPromise()
       .then(res => console.log(res.json()), err => console.log(err));
   }

}

1 个答案:

答案 0 :(得分:4)

如果test方法返回一个observable,你需要以与promises类似的方式订阅它:

this._sampleService.test()
   .subscribe(
     data => this.countries = data,
     error => this.error = "Region " + this.region + " is invalid."
   );

例如对于这样的test方法:

test() {
  return this.http.get('http://...').map(res => res.json());
}

你可以注意到你也可以使用Angular2的promises。在这种情况下,您将以与您相同的方式处理响应。

修改

您可以通过以下方式更新test方法:

test(){
  console.log(AppSettings.API_ENDPOINT);
  return this.http.get(AppSettings.API_ENDPOINT+"oceania")
               .map(res => console.log(res.json());
 }

并将其称为:

this.service.test().subscribe(data => {
  (...)
});

如果您想利用承诺,您需要在then回调中返回一些内容以利用链接:

test(){
  console.log(AppSettings.API_ENDPOINT);
  return this.http.get(AppSettings.API_ENDPOINT+"oceania").toPromise()
    .then(res => res.json(), err => console.log(err)); // <---------
}

您可以通过这种方式获取数据:

this.service.test().then(data => {
  (...)
});