2017-04-01 3 views
0

여기에 일부 코드가 있습니다. 응용 프로그램을 만들었지 만 배열 객체로 작업하는 방법에 걸림돌이됩니다. NgInit {} 위의 코드를 제공했습니다. Xcode에서 TS 오류가 발생했습니다.오브젝트를 오브젝트 배열에 넣기 - 입력 스크립트

전체 구성이 아래 코드에서 어떤 일이 일어나고

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; }[]'. 

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) { 

    } 

오류가 발생했습니다. 내가 뭘 하려는지이 개체를 개체 배열에 밀어 넣어 같은 속성에 액세스 할 수 있습니다.

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

갱신 게시물 – Aravind

답변

1

coinResultsresultsType의 배열로 선언, 그래서 그것은 단지 resultsType 형의 인수를 받아들이는 push 방법입니다. 그러나, 당신은 (대괄호주의) 배열 coinResults-resultsType을 추진하려는 : var temp=... 라인에서 객체 리터럴 주위

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

느슨한 대괄호.

0

배열 매개 변수 push(...items: T[])으로 Array.push 서명을 정의 했으므로 Array.push(array)에 배열을 전달할 수 없습니다. 대신 Array.push (item)을 사용하십시오.

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

또는 사용 확산 : 연산자 ** resultsType ** 코드 ...

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