【问题标题】:"Property 'rates' has no initializer and is not definitely assigned in the constructor"“属性 'rates' 没有初始化程序,也没有在构造函数中明确分配”
【发布时间】: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
}

【问题讨论】:

  • 用空对象初始化ratesrates: {[key: string]: number} = {};

标签: angular typescript


【解决方案1】:

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

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

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

【讨论】:

  • 它有一个构造函数,但它没有为那里的费率赋值
  • @Lesiak-Doh!谢谢。我没有向下滚动足够远!
  • 另外值得一提的是,在较旧的 Angular 项目中,如果您禁用了严格的空值检查,则 OP 中提供的代码将起作用。
  • 哇!太感谢了!! :D Angular 变得很有趣 ;)
猜你喜欢
  • 2021-04-13
  • 2021-05-06
  • 2021-08-14
  • 2021-02-28
  • 2021-12-25
相关资源
最近更新 更多