typescript – 如何从angular2中的observable获取数据
发布时间:2020-12-17 08:04:56 所属栏目:安全 来源:网络整理
导读:我试图使用rxjs在Angular中打印http调用的结果 请考虑以下代码 import { Component,Injectable,OnInit } from '@angular/core';import { Http,HTTP_PROVIDERS } from '@angular/http';import 'rxjs/Rx';@Injectable()class myHTTPService { constructor(priv
我试图使用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的结果?
您需要订阅observable并传递一个处理发出值的回调
this.myService.getConfig().subscribe(val => console.log(val)); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |