gpt4 book ai didi

javascript - 将对象插入对象数组 - Typescript

转载 作者:行者123 更新时间:2023-12-03 04:39:16 24 4
gpt4 key购买 nike

这里的一些代码遇到问题。构建应用程序,但在如何使用数组对象方面遇到困难。我在 NgInit{} 上面提供了代码。并提供了我在 Xcode 中遇到的 TS 错误。

完整组件

import { Component, OnInit } from '@angular/core';
import { Ticker } from '../TickerType';
import { ConversionService } from '../Conversion.service';
import {Observable} from 'rxjs/Rx';
import {resultsType} from './resultsTypeInterface';
@Component({
selector: 'app-contents',
templateUrl: './contents.component.html',
styleUrls: ['./contents.component.scss']
})
export class ContentsComponent implements OnInit{

//Will hold the data from the JSON file


// Variables for front end
cryptoSelected : boolean = false;
regSelected : boolean = false;
step2AOptions : any[] = [
{name: "make a selection..."},
{name: "Bitcoin"},
{name: "DASH"},
{name: "Etherium"}
]; // step2AOptions
step2BOptions : any[] = [
{name: "make a selection..."},
{name: "CAD"},
{name: "USD"}
]; // step2BOptions
step2Selection: string;
holdings: number = 10;

coins: any[] = ["BTC_ETH", "BTC_DASH"];
ticker: Ticker[];
coinResults: resultsType[] =[];
currencyExchange:any[] = [];

constructor( private conversionService: ConversionService ) {

}

错误

Argument of type '{ name: string; amount: any; }[]' is not assignable to parameter of type 'resultsType'.
Property 'name' is missing in type '{ name: string; amount: any; }[]'.

这发生在下面的代码中。我想做的是将这个对象插入对象数组中,这样我就可以访问类似的属性。

console.log(coinsResults[0].name);

代码

ngOnInit(){
this.conversionService.getFullTicker().subscribe((res) => {this.ticker = res;

for(var j = 0; j<= this.coins.length-1; j++)
{
var currencyName: string = this.coins[j];
if(this.ticker[currencyName])
{
var temp = [{name: currencyName, amount: this.ticker[currencyName].last} ]
this.coinResults.push(temp)
}
}//end the for loop
}); //end the subscribe function
this.conversionService.getFullCurrencyExchange().subscribe( (res) => {this.currencyExchange = res["rates"]
});
console.log(this.coinResults);
}// End OnInit

最佳答案

coinResults 被声明为 resultsType 数组,因此它的 push 方法仅接受 resultsType 参数类型。但是,您尝试将resultsType数组推送到coinResults(注意方括号):

// temp is resultsType[]
var temp = [{name: currencyName, amount: this.ticker[currencyName].last} ]
// but coinResults.push() accept only resultsType
this.coinResults.push(temp)

松开 var temp=... 行中对象文字两边的方括号。

关于javascript - 将对象插入对象数组 - Typescript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43151527/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com