-1

我正在尝试创建一个类似于 Google 的货币转换器应用程序,即

在此处输入图像描述

我的挑战是我必须处理的来自 fixer.io 的数据需要重新处理才能完成上述 Google 转换器。我只能使用来自 fixer.io 的以下端点,即http://data.fixer.io/api/latest ? access_key=....

我下面的代码可能会解释得更好一些。我还在这里创建了一个 stackblitz https://stackblitz.com/edit/angular-9-material-starter-o9yvuu?file=src/app/app.component.ts

服务

//list endpoint from Fixer.io
currencyRates(): Observable<any> {
    return this.http.get(this.baseURL + this.accessKey);
}

TS

  //call endpoint and manipulate data to use on HTML
  public currencies: any;
  public currenciesArr: any;

  getCurrencies() {
    this.currencyService.currencyRates().subscribe({
      next: (v) => {
        this.currencies = v;
        let result = Object.keys(this.currencies.rates).map((key) => 
          [String(key), this.currencies.rates[key]]
        );
        this.currenciesArr = result;
        console.log(this.currenciesArr);
      },
      error: (e) => console.error(e),
      complete: () => console.info('complete') 
   });
  }

HTML

    <mat-form-field class="form-field" appearance="outline">
      <mat-label> Input Currency
      </mat-label>
      <input matInput formControlName="input" required>
    </mat-form-field>
    <mat-form-field appearance="fill">
        <mat-label>Select an option</mat-label>
        <mat-select >
          <mat-option *ngFor="let item of currenciesArr" [value]="item">{{item}}</mat-option>
        </mat-select>
    </mat-form-field>
    <mat-form-field class="form-field" appearance="outline">
      <mat-label> Output Currency
      </mat-label>
      <input matInput formControlName="output" type="output" required>
    </mat-form-field>
    <mat-form-field appearance="fill">
      <mat-label>Select an option</mat-label>
      <mat-select >
        <mat-option *ngFor="let item of currenciesArr" [value]="item">{{item}}</mat-option>
      </mat-select>
  </mat-form-field>

最初来自端点的数据如下所示,我随后对其进行了转换,以便在我的下拉框中使用。在我的 TS 中使用Object.keys.

{
    "success": true,
    "timestamp": 1645249562,
    "base": "EUR",
    "date": "2022-02-19",
    "rates": {
        "AED": 4.158769,
        "AFN": 104.057478,
        "ALL": 121.54654
    }
}

我现在对如何进一步操作数据感到困惑,以便我可以在下拉列表中显示货币名称,并在输入字段中显示货币的实际价值。任何人都可以在这里帮助我吗?

我目前在想我需要创建 2 个数组。一次是货币名称,另一个是价值,但我很迷茫。

4

1 回答 1

0

好的,所以你拥有的数据就足够了,你只需要一些体操:)

首先,我会创建一个货币对象数组(例如:),allCurrencies每个对象都具有以下结构:{ currency: 'XYZ', baseRate: '1234' }其中“XYZ”是取自“汇率”字段的货币名称,“1234”是给定货币(兑欧元)。

其次,在模板中,我将遍历该数组并将下拉选项设置为“货币”值。或者,我会将输出货币输入字段设为只读。

第三,当“输入货币”被更改/设置并且相应的文本输入不为空/空时,我会立即(在 .ts 中)根据allCurrencies该“货币”的“baseRate”将金额转换为欧元。我们称这个新金额convertedOriginal

第四,当“输出货币”改变时(如果选择“输入货币”并且相应的文本输入不为空/空),我会将convertedOriginal值转换为所选输出货币的汇率。

于 2022-02-19T06:55:33.167 回答