Angular 2 Http 获取响应示例 [英] Angular 2 Http Get Response Example
问题描述
从 Angular 2 中的 http get 获取 json 数据的正确方法是什么.我正在使用模拟端点测试一些本地数据,我可以在 http.get()<中看到结果/code> 但我无法在本地分配它或者存在一些时间问题.这是我的简单服务:
What is the correct way to get json data from an http get in Angular 2. I am working on testing some local data with a mocked endpoint, and I can see the result in the http.get()
but I cannot assign it locally or there is some timing issue. Here is my simple service:
import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map'; // we need to import this now
@Injectable()
export class MyHttpService {
constructor(private _http:Http) {}
getDataObservable(url:string) {
return this._http.get(url)
.map(data => {
data.json();
console.log("I CAN SEE DATA HERE: ", data.json());
});
}
}
这是我尝试分配数据的方式:
And here is how i'm trying to assign the data:
import {Component, ViewChild} from "@angular/core";
import { MyHttpService } from '../../services/http.service';
@Component({
selector: "app",
template: require<any>("./app.component.html"),
styles: [
require<any>("./app.component.less")
],
providers: []
})
export class AppComponent implements OnInit, AfterViewInit {
private dataUrl = 'http://localhost:3000/testData'; // URL to web api
testResponse: any;
constructor(private myHttp: MyHttpService) {
}
ngOnInit() {
this.myHttp.getDataObservable(this.dataUrl).subscribe(
data => this.testResponse = data
);
console.log("I CANT SEE DATA HERE: ", this.testResponse);
}
}
我可以在 get() 调用中看到我想要的数据,但在调用之后我似乎无法访问它...请告诉我我做错了什么!
I can see the data I want in the get() call but I don't seem to have access to it after that call...please tell me what i'm doing wrong!
推荐答案
这不应该是这样的.当数据到达时,传递给可观察对象的回调被调用.需要访问此数据的代码必须在回调中.
That's not supposed to work this way. When the data arrives the callback passed to the observable is called. Code that needs to access this data has to be inside the callback.
ngOnInit() {
this.myHttp.getDataObservable(this.dataUrl).subscribe(
data => {
this.testResponse = data;
console.log("I CANT SEE DATA HERE: ", this.testResponse);
}
);
}
更新
getDataObservable(url:string) {
return this._http.get(url)
.map(data => {
data.json();
// the console.log(...) line prevents your code from working
// either remove it or add the line below (return ...)
console.log("I CAN SEE DATA HERE: ", data.json());
return data.json();
});
}
这篇关于Angular 2 Http 获取响应示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!