简体   繁体   English

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

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

I am using fixer.io and money.js to convert currency. 我正在使用fixer.io和money.js转换货币。 money.js is used to convert currency and fixer.io is an api that gets the latest exchange rates. money.js用于转换货币,fixer.io是获取最新汇率的api。 I need to load the latest exchange rates into the money.js rates object. 我需要将最新汇率加载到money.js汇率对象中。

Because I'm using angular, money.js is loaded like: 因为我使用的是angular,所以money.js的加载方式如下:

var fx = require("money");

In order for conversion to work, we have to define fx.base and fx.rates like this: 为了使转换fx.base ,我们必须定义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 */
} 

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 但是,不是将fx.rates硬编码数据从GET请求填充到fixer.io API,该API会返回以下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. 我是一个角度的菜鸟,所以我不明白如何将json响应加载到另一个json对象中。

What is the right way to do something like : 什么是做这样的正确方法:

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

It's quite easy, using the http promise in Angular. 使用Angular中的http promise很容易。 To handle a promise, you use the .then method. 要处理承诺,请使用.then方法。 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. 如果需要,这是工作中的plnkr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM