簡體   English   中英

使用angular2讀取JSON

[英]read JSON using angular2

我在使用json \\ object時遇到問題,我試圖從中提取數據,但失敗了。

我有這個API,可以從中提取數據: http : //api.fixer.io/latest?base=CAD

我把它放在可變的results ,如果我想得到對象的參數日期,基准,利率,如下所示:

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());
  }

嘗試更新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))

服務請求是異步的,因此請求的結果是一個Promise,它解析為一個對象,而不是對象本身。 嘗試這樣的事情:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM