2016-10-27 64 views
-1

我有json \對象的問題我試圖從中拉出數據,我失敗了。閱讀JSON使用angular2

我有這個API,我拉離我的數據: http://api.fixer.io/latest?base=CAD

我已經把它放在變量results, 如果我想反對paramater迄今爲止,基地,率象下面這樣:

calc(details) { 
    let results = [this.networkServices.getCurrency(details)]; // object is here "getCurrency deal with the GET request. 
    alert(results.base); 
} 

我得到的錯誤代碼:

[02:58:36] transpile update started ... 
[02:58:38] typescript: D:/ionic/firstApp/src/pages/currency/currency.ts, line: 19 
      Property 'base' does not exist on type 'Promise<any>[]'. 

     L18: let results = [this.networkServices.getCurrency(details)]; 
     L19: alert(results.base); 

[02:58:38] transpile update failed 

它覺得不可思議,我不能拉數據出來了,它會是什麼?

獲得貨幣功能

getCurrency(obj){ 
    console.log("function fired!") 
    let url = `http://api.fixer.io/latest?base=${obj.selectedCurrency}`; 
    return this.http.get(url).toPromise().then(res => res.json()); 
    } 
+0

請使用網絡服務的getCurrency()方法更新 –

+0

這與Angular有什麼關係?這與JSON有什麼關係? –

回答

1

該服務請求是異步的,從而該請求的結果是解析爲一個對象,而不是對象本身的承諾。嘗試是這樣的:

this.networkServices.getCurrency(details).then(result => alert(result)) 
+0

angular2不接受。然後,它用紅色標記他.. – itzikb

+0

什麼是錯誤? – pe8ter

2

嘗試更新getCurrency()通過去除then()只返回承諾:

getCurrency(obj){ 
    console.log("function fired!") 
    let url = `http://api.fixer.io/latest?base=${obj.selectedCurrency}`; 
    return this.http.get(url).toPromise(); 
    } 

然後從@ pe8ter解決方案應該工作:

this.networkServices.getCurrency(details).then(result => alert(result))