read JSON using angular2

2019-12-16 20:13发布

问题:

I have problem with json\object I'M trying to pull the data out from it and I failed.

I have this API that I pull my data from: 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:

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

回答1:

The service request is asynchronous so the result of the request is a Promise that resolves to an object, not the object itself. Try something like this:

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


回答2:

Try updating your getCurrency() to just return the promise by removing the 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:

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



标签: json angular