0

我正在使用 API 来获取货币汇率。用户正在输入基础和输出货币。

这是我的后端:

    import {fetch} from 'wix-fetch';  


export function getCurrency(currency,baseCurrency) {
    const url = 'https://api.fixer.io/latest?base=';

    let fullUrl = url + baseCurrency + '&symbols=' + currency;

    return fetch(fullUrl, {method: 'get'})
      .then(response => response.json())
      .then(json => json.rates[currency].toString());
}

这是我的页面代码:

    import {getCurrentTemp, getCurrency} from 'backend/ArenaApi';

export function button1_click(event, $w) {
    getCurrency($w("#currencysymbol").value,$w("#baseCurrency").value)
  .then(rates => $w("#currencyrate").text = "1 " + ($w("#baseCurrency").value) + " = " + rates + " " + ($w("#currencysymbol").value));
    $w("#currencyrate").show();
}

据我了解,我的后端正在获取这些数据:

"base":"USD","date":"2018-05-22","rates":{"EUR":0.84789}

它正在通过后端的以下行从该字符串中检索“费率” :

.then(json => json.rates[currency].toString());

我想知道如何从单个字符串中检索多个值?对于这种情况:“rates” “base” “date”,然后将其注入到页面中的文本元素中,例如:

.then(rates => $w("#currencyrate").text = "1 " + ($w("#baseCurrency").value) + " = " + rates + " " + ($w("#currencysymbol").value));
4

1 回答 1

0

首先将整个 JSON 返回到页面代码,而不仅仅是后端代码中的费率:

import {fetch} from 'wix-fetch';  

export function getCurrency(currency,baseCurrency) {
  const url = 'https://api.fixer.io/latest?base=';
  let fullUrl = url + baseCurrency + '&symbols=' + currency;

  return fetch(fullUrl, {method: 'get'})
    .then(response => response.json());
}

现在您已经拥有了页面代码可用的所有内容,您可以从中提取任何您想要的内容。例如:

import {getCurrentTemp, getCurrency} from 'backend/ArenaApi';

export function button1_click(event, $w) {
  const currency = $w("#currencysymbol").value;
  const baseCurrency = $w("#baseCurrency").value;

  getCurrency(currency, baseCurrency)
    .then( (json) => {
      $w("#base").text = json.base;
      $w("#date").text = json.date;
      $w("#rate").text = json.rates[currency].toString 
    });

}

于 2018-05-23T10:16:37.240 回答