Basic Angular - How to load json http response into another json object

632 views Asked by At

I am using fixer.io and money.js to convert currency. money.js is used to convert currency and fixer.io is an api that gets the latest exchange rates. I need to load the latest exchange rates into the money.js rates object.

Because I'm using angular, money.js is loaded like:

var fx = require("money");

In order for conversion to work, we have to define fx.base and fx.rates like this:

fx.base = "USD";
fx.rates = {
    "EUR" : 0.745101, // eg. 1 USD === 0.745101 EUR
    "GBP" : 0.647710, // etc...
    "HKD" : 7.781919,
    "USD" : 1,        // always include the base rate (1:1)
    /* etc */
} 

However, rather than hardcoded data for fx.rates to be populated from a GET request to the fixer.io API, which will return this JSON: http://api.fixer.io/latest

I'm a total noob to angular so I don't understand how to load a json response into another json object.

What is the right way to do something like :

var response = $http.get("http://api.fixer.io/latest");
fx.rates = response;
1

There are 1 answers

3
CozyAzure On

It's quite easy, using the http promise in Angular. To handle a promise, you use the .then method. All you need is a callback function to handle the data. :

var response = $http.get("http://api.fixer.io/latest");

//handle promise
response.then(function(response) {
  //this is response from the api fixer. The data is the body payload
  fx.rates = response.data;
}, function(error) {
  //handle error here, if there is any.
});

Here is the working plnkr, if you need it.