2017-04-01 147 views
0

在這裏遇到了一些代碼的麻煩。構建一個應用程序,但卻陷入瞭如何處理數組對象的問題。我提供了NgInit {}以上的代碼。並提供了我在Xcode中獲得的TS錯誤。將對象推入對象數組 - Typescript

全部組分

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 
+0

更新您的文章與** ** resultsType代碼 – Aravind

回答

1

coinResults被聲明爲resultsType數組,所以它的push方法將只接受resultsType類型的參數。但是,你要推數組resultsTypecoinResults(注意括號):

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

寬鬆的方括號中的對象var temp=...行文字。

0

由於Array.push簽名定義爲重置參數push(...items: T[]),因此您不能將數組傳遞給Array.push(array),請改用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);