我正在尝试创建一个类似于 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 个数组。一次是货币名称,另一个是价值,但我很迷茫。