“属性 'rates' 没有初始值设定项,并且在构造函数中没有明确分配”

时间:2021-02-18 15:51:57

标签: angular typescript

我正在尝试制作尽可能多的项目以进入工作流程。在这个项目中,我正在尝试做一个货币转换器,但它的汇率似乎有问题。有没有人知道我做错了什么?

它在 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
}

1 个答案:

答案 0 :(得分:1)

rates: {[key: string]: number}; 声明 rates 属性并为其指定类型,但未为其指定初始值。您的类的构造函数也没有为 rates 分配任何内容,并且类型不允许 undefined(属性的默认值),因此错误是它从未初始化为任何内容。

给定你分配给它的类型,你可以用一个空白对象初始化它;

rates: {[key: string]: number} = {};
// −−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^