网站搜索

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


在这里处理一些代码遇到麻烦。正在构建一个应用程序,但在如何处理数组对象时遇到困难。我在 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

答案#1

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=... 行中对象字面量周围的方括号。

答案#2

你不能将一个数组传递给 Array.push(array),因为 Array.push 的签名定义为可变参数 push(...items: T[]),应该使用 Array.push(item) 代替。

var temp = {name: currencyName, amount: this.ticker[currencyName].last}; 
this.coinResults.push(temp);

或者使用展开运算符:...

var temp = [{name: currencyName, amount: this.ticker[currencyName].last} ];
this.coinResults.push(...temp);