[英]Angular 2 Http Get Response Example
在Angular 2中從http獲取json數據的正確方法是什么。我正在使用http.get()
端點測試一些本地數據,我可以在http.get()
看到結果,但我不能在本地分配它或有一些時間問題。 這是我的簡單服務:
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());
});
}
}
以下是我試圖分配數據的方式:
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()調用中看到我想要的數據但是在調用之后我似乎無法訪問它...請告訴我我做錯了什么!
這不應該以這種方式工作。 當數據到達時,調用傳遞給observable的回調。 需要訪問此數據的代碼必須位於回調內。
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();
});
}
因為http調用是異步的。 您需要在訂閱功能中進行分配。 試試這樣:
this.myHttp.getDataObservable(this.dataUrl).subscribe(
data => {
this.testResponse = data ;
console.log("I SEE DATA HERE: ", this.testResponse);
}
);
這是一個易於使用的示例,允許您使用promises。
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Config } from '../Config';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
@Injectable()
export class Request {
constructor(public http: Http)
{
}
get(url): Promise<any>
{
return this.http.get(Config.baseUrl + url).map(response => {
return response.json() || {success: false, message: "No response from server"};
}).catch((error: Response | any) => {
return Observable.throw(error.json());
}).toPromise();
}
post(url, data): Promise<any>
{
return this.http.post(Config.baseUrl + url, data).map(response => {
return response.json() || {success: false, message: "No response from server"};
}).catch((error: Response | any) => {
return Observable.throw(error.json());
}).toPromise();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.