使用angular2读取JSON

时间:2016-10-27 23:57:48

标签: json angular

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

2 个答案:

答案 0 :(得分: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))

答案 1 :(得分:1)

服务请求是异步的,因此请求的结果是一个解析为对象的Promise,而不是对象本身。尝试这样的事情:

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