简体   繁体   English

使用angular2读取JSON

[英]read JSON using angular2

I have problem with json\\object I'M trying to pull the data out from it and I failed. 我在使用json \\ object时遇到问题,我试图从中提取数据,但失败了。

I have this API that I pull my data from: http://api.fixer.io/latest?base=CAD 我有这个API,可以从中提取数据: http : //api.fixer.io/latest?base=CAD

I have placed it on variable results , If i want to get to object paramater date,base,rate like below: 我把它放在可变的results ,如果我想得到对象的参数日期,基准,利率,如下所示:

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

I get the error code: 我收到错误代码:

[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 

Its feel weird that I can't pull the data out, what could it be? 我无法提取数据感到很奇怪,那会是什么?

get currency function 获取货币功能

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

Try updating your getCurrency() to just return the promise by removing the then() : 尝试更新getCurrency()以通过删除then()来返回承诺:

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

Then the solution from @pe8ter should work: 然后@ pe8ter的解决方案应该起作用:

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

The service request is asynchronous so the result of the request is a Promise that resolves to an object, not the object itself. 服务请求是异步的,因此请求的结果是一个Promise,它解析为一个对象,而不是对象本身。 Try something like this: 尝试这样的事情:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM