如何从angular2中的observable获取数据

时间:2016-04-04 05:40:18

标签: typescript angular reactive-programming rxjs observable

我正在尝试使用http

Angular打印rxjs来电的结果

考虑以下代码

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的结果?

3 个答案:

答案 0 :(得分:55)

您需要订阅observable并传递一个处理发出值的回调

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

答案 1 :(得分:14)

Angular基于angularjs 1.x中的observable而不是promise base,因此当我们尝试使用http获取数据时,它返回observable而不是promise,就像你做的那样

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

然后获取数据并在视图中显示我们必须使用像.map() function and .subscribe()

这样的RxJs函数将其转换为所需的形式

.map()用于将observable(从http请求接收)转换为Angular官方网站中所述的.json(), .text()之类的任何形式,

.subscribe()用于订阅那些可观察的响应,并将ton放入一些变量中,以便我们将其显示在视图中

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

答案 2 :(得分:13)

this.myService.getConfig().subscribe(
  (res) => console.log(res),
  (err) => console.log(err),
  () => console.log('done!')
);
相关问题