2017-04-01 143 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);