簡體   English   中英

將對象推入對象數組-打字稿

[英]Pushing objects into Object Array - 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; }[]'.

這在下面的代碼中發生。 我想做的是將這個對象推入一個對象數組,以便可以訪問like的屬性。

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=...行中對象文字的方括號。

您不能將數組傳遞給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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM