1

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 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Does this work even if the json includes other fields? If you look at the Json response for that URL, it also includes a base attribute and a date attribute, and then the rates. So isn't what I really need more like fx.rates = response.data.rates
One more question- also does the $http promise have to be in a controller?
Yes. The response.data includes every thing in the payload body. So if the data has 1000 properties, it will contain every single one of them. $http is a service that is injected into the controller, as shown in the plnkr

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.