javascript - Basic Angular - 如何将 json http 响应加载到另一个 json 对象中

标签 javascript angularjs json http currency-exchange-rates

我正在使用 fixer.io 和 money.js 来转换货币。 money.js 用于转换货币,而 fixer.io 是一个获取最新汇率的 api。我需要将最新的汇率加载到 money.js rates 对象中。

因为我使用的是 angular,所以 money.js 的加载方式如下:

var fx = require("money");

为了进行转换,我们必须像这样定义 fx.basefx.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/

相关文章:

javascript - MVC3 Razor : call javascript function from view

javascript - 当 jQuery 元素附加到 DOM 时触发 OnAppend 事件

javascript - 如何使用表单数据打印值?

json - 如何将自定义编码器添加到 akka http?

sql - 如何完全在 BigQuery 中创建具有嵌套架构的新表

java - 如何使用 Binary Builder 动态地将 JSON 插入 Apache Ignite Cache(没有 Java 类)?

javascript - 编码uri组件,不自动解码

javascript - 全部居中并根据数据长度调整excel列

javascript - Angular,需要通过多种形式检查 Controller

javascript - 无法通过 Node.js 将 Heroku 配置变量传递到 Angular CLI 应用程序