tes*_*ing 53 reactive-programming observable rxjs typescript angular
我正在尝试打印使用中的http调用结果Angularrxjs
请考虑以下代码
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());
}
}
Run Code Online (Sandbox Code Playgroud)
每当我试图打印出getconfig它的结果总是返回
Observable {_isScalar: false, source: Observable, operator: MapOperator}
Run Code Online (Sandbox Code Playgroud)
即使我返回一个json对象.
我怎么打印出结果getConfig?
Gün*_*uer 71
您需要订阅observable并传递一个处理发出值的回调
this.myService.getConfig().subscribe(val => console.log(val));
Run Code Online (Sandbox Code Playgroud)
Par*_*ain 18
Angular是基于angularjs 1.x的observable而不是promise base,所以当我们尝试使用http它来获取数据时,返回observable而不是promise,就像你做的那样
return this.http
.get(this.configEndPoint)
.map(res => res.json());
Run Code Online (Sandbox Code Playgroud)
然后要获取数据并在视图上显示我们必须使用RxJs函数将其转换为所需的形式 .map() function and .subscribe()
.map()用于将observable(从http请求接收)转换.json(), .text() 为Angular官方网站中所述的任何形式,
.subscribe()用于订阅那些可观察的响应和ton放入一些变量,以便我们将它显示到视图中
this.myService.getConfig().subscribe(res => {
console.log(res);
this.data = res;
});
Run Code Online (Sandbox Code Playgroud)
mic*_*yks 15
this.myService.getConfig().subscribe(
(res) => console.log(res),
(err) => console.log(err),
() => console.log('done!')
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
109809 次 |
| 最近记录: |