如何从angular2中的可观察数据中获取数据 [英] How to get data from observable in angular2
本文介绍了如何从angular2中的可观察数据中获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用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
的结果时,它总是返回
Whenever I tried to print out the result of getconfig
it always return
Observable {_isScalar: false, source: Observable, operator: MapOperator}
即使我返回一个json对象.
even though I return a json object instead.
我如何打印getConfig
的结果?
推荐答案
您需要订阅可观察对象,并传递一个处理发出的值的回调
You need to subscribe to the observable and pass a callback that processes emitted values
this.myService.getConfig().subscribe(val => console.log(val));
这篇关于如何从angular2中的可观察数据中获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文