从 API 调用中检索值 |蜡

Retrieving values from an API call | Wix

我正在使用 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}

它正在通过后端中的以下行从此字符串中检索 "rates"

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

我想知道如何从单个字符串中检索多个值?对于此实例:"rates" "base" "date" 和然后将其注入页面中的文本元素,如:

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

首先将整个 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 
    });

}