2016-10-27 63 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))