我正在使用 fixer.io 和 money.js 来转换货币。 money.js 用于转换货币,而 fixer.io 是一个获取最新汇率的 api。我需要将最新的汇率加载到 money.js rates 对象中。
因为我使用的是 angular,所以 money.js 的加载方式如下:
var fx = require("money");
为了进行转换,我们必须像这样定义 fx.base
和 fx.rates
:
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 */
}
但是,不是将 fx.rates
的硬编码数据从 GET 请求填充到 fixer.io API,它将返回此 JSON:
http://api.fixer.io/latest
我对 Angular 完全是菜鸟,所以我不明白如何将 json 响应加载到另一个 json 对象中。
什么是正确的方法来做这样的事情:
var response = $http.get("http://api.fixer.io/latest");
fx.rates = response;
最佳答案
这很容易,使用 http
promise在 Angular 。要处理 promise ,您可以使用 .then
方法。您只需要一个回调函数来处理数据。 :
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.
});
这是 working plnkr , 如果你需要的话。
关于javascript - Basic Angular - 如何将 json http 响应加载到另一个 json 对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41133134/