【发布时间】:2021-05-21 14:36:39
【问题描述】:
我正在尝试制作尽可能多的项目以进入工作流程。在这个项目中,我正在尝试做一个货币转换器,但汇率似乎有问题。有谁知道我做错了什么?
它在OnInit 中的费率 - 它抱怨。
这是我的主要组件
import { Component, OnInit } from '@angular/core';
import {CurrencyExchangeService} from '../services/exchange-rates.service';
@Component({
selector: 'app-valutaomraknare',
templateUrl: './valutaomraknare.component.html',
styleUrls: ['./valutaomraknare.component.scss']
})
export class ValutaomraknareComponent implements OnInit {
amount = 1;
from = 'CAD';
to = 'USD';
rates: {[key: string]: number};
convert(): number{
return this.amount * this.rates[this.to];
}
loadRates(){
this.service.getRates(this.from).subscribe(res => this.rates = res.rates);
}
getAllCurrencies(): string[]{
return Object.keys(this.rates);
}
constructor(private service: CurrencyExchangeService) {
}
ngOnInit(): void {
this.loadRates();
}
}
汇率服务
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { ExchangeRatesResponse } from './interface/exchange-rates-response';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class CurrencyExchangeService {
constructor(private http: HttpClient) { }
getRates(base: string): Observable<ExchangeRatesResponse> {
return this.http.get<ExchangeRatesResponse>(`https://api.exchangeratesapi.io/latest?base=${base}`);
}
}
汇率反应
export interface ExchangeRatesResponse {
rates: {
[key: string]: number
},
base: string,
date: string
}
【问题讨论】:
-
用空对象初始化
rates:rates: {[key: string]: number} = {};
标签: angular typescript