如何在Angular2中从Observable获取数据

89
我试图使用rxjs在Angular中打印http调用的结果。考虑以下代码。
import { Component, Injectable, OnInit } from '@angular/core';
import { Http, HTTP_PROVIDERS } from '@angular/http';
import 'rxjs/Rx';

@Injectable()
class myHTTPService {
  constructor(private http: Http) {}

  configEndPoint: string = '/my_url/get_config';

  getConfig() {

    return this.http
      .get(this.configEndPoint)
      .map(res => res.json());
  }
}

@Component({
    selector: 'my-app',
    templateUrl: './myTemplate',
    providers: [HTTP_PROVIDERS, myHTTPService],


})
export class AppComponent implements OnInit {

    constructor(private myService: myHTTPService) { }

    ngOnInit() {
      console.log(this.myService.getConfig());
    }
}
无论何时我尝试打印getconfig的结果,它总是返回
Observable {_isScalar: false, source: Observable, operator: MapOperator}

即使我返回了一个 JSON 对象,也可以。

如何打印 getConfig 的结果?


你得到解决方案了吗? - ramya
3个回答

122

您需要订阅可观察对象并传递一个回调函数来处理发出的值。

this.myService.getConfig().subscribe(val => console.log(val));

1
它应该是res.json()而不是res.json - Pardeep Jain
嗯,但是您还没有提到它,所以请发表评论。 - Pardeep Jain
不确定您上一条评论的意思。问题中的代码已经包含了它。当您订阅时,无需再次转换为JSON。 - Günter Zöchbauer
嗯,我只想说我们需要在 .map() 或 .json() 的时候进行转换。 - Pardeep Jain
console.log(JSON.stringify(val)) - bmusical

28

Angular基于可观察对象而不是Promise(承诺)基础,与AngularJS 1.x不同,因此当我们尝试使用http获取数据时,它返回可观察对象而不是Promise,就像您所做的那样。

 return this.http
      .get(this.configEndPoint)
      .map(res => res.json());

为了获得数据并在视图中显示,我们需要使用RxJs函数(例如.map()函数和.subscribe())将其转换为所需的形式。

.map()用于将Observable(从HTTP请求接收到的)转换为任何形式,例如官方网站中所述的.json(),.text()

.subscribe()用于订阅这些Observable响应并将其放入某个变量中,以便我们将其显示在视图中。

this.myService.getConfig().subscribe(res => {
   console.log(res);
   this.data = res;
});

如果服务需要一些时间才能返回数据,而你需要在下一个函数中使用this.data怎么办? - rahularyansharma
你可以使用async/await,也可以在http服务调用中调用下一个函数。两种方法都应该有效。 - Pardeep Jain

18
this.myService.getConfig().subscribe(
  (res) => console.log(res),
  (err) => console.log(err),
  () => console.log('done!')
);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接