我從角度4和服務器端渲染開始,目前我正在試圖獲取概念驗證,以獲取我的外部API之一的某些數據。該API返回一個Json對象。在Angular 4中獲取數據
該網站呈現相當不錯,但現在,我包括調用來獲取數據它沒有呈現和我得到的反應似乎並不是我應該得到的。
在app.components.ts我說:現在
private apiUrl= 'https://myapi/Users';
data: any = {};
constructor(private http: Http){
this.getUsers();
this.getData();
}
getData(){
let res=this.http.get(this.apiUrl).map((res: Response)=>res.json());
console.log("result:",res)
return res;
}
getUsers(){
this.getData().subscribe(data=>{
this.data=data;
})
}
,你可以看到,在GetData方法,我在控制檯打印HTTP調用的結果,但我得到這個:
Observable {
_isScalar: false,
source: Observable { _isScalar: false, _subscribe: [Function] },
operator: MapOperator { project: [Function], thisArg: undefined } }
爲什麼我沒有去那裏的json對象?這可能是原因?
這是正確的。你的'res'實際上是一個'Observable',而不是數據本身。觀察對象是異步的。要查看真實的數據,請在'subscribe()'處查看'console.log'。回調函數,或者你可以在你的'map'回調函數中查看它。 – CozyAzure