2017-03-07 24 views
0

我有一個僱員對象,我想複製一些值到一個新的對象。我正在使用Typescript來複制它們,但我得到錯誤。Angular 2 - 無法將值從一個對象複製到另一個使用打字稿

打字稿代碼:

employee = [ 
    { "empId": "59C", "empDesc": "Software","location":"Dallas"}, 
    { "empId": "AMI", "empDesc": "Hardware", "location":"San Francisco"} 
    ]; 
    companies : any; 
    for (let c of this.employee) { 
     this.companies.push({ 
     empDesc: c.empDesc, 
     empId: c.empId 
     }) 
    }; 
    console.log("Companies",this.companies); 

Plunker代碼鏈接:

https://plnkr.co/edit/CnBR4JouNhzH3DWm7QCo?p=preview

回答

2

你需要運行在一個函數的代碼。在這裏我正在構造函數中運行它。您只能在類中聲明變量。

還需要用空數組初始化companies

employee = [ 
    { "empId": "59C", "empDesc": "Software","location":"Dallas"}, 
    { "empId": "AMI", "empDesc": "Hardware", "location":"San Francisco"} 
    ]; 
    companies : any = []; 


    constructor(){ 
    for (let c of this.employee) { 
     this.companies.push({ 
     empDesc: c.empDesc, 
     empId: c.empId 
     }) 
    }; 
    console.log("Companies",this.companies); 

    } 
2

有幾個問題,

你必須編寫代碼iside一些功能

constructor(){ 
    for (let c of this.employee) { 
     this.companies.push({ 
     empDesc: c.empDesc, 
     empId: c.empId 
     }) 
    }; 
    console.log("Companies",this.companies); 
} 

和初始化公司財產,

退房更新Plunker!!

希望這可以幫助!!

0

這爲我工作:

public employee: any[] = []; 
public companies: any[] = []; 

ngOnInit() { 
    this.employee = [ 
    { "empId": "59C", "empDesc": "Software","location":"Dallas"}, 
    { "empId": "AMI", "empDesc": "Hardware", "location":"San Francisco"} 
    ]; 


    for (let c of this.employee) { 
     let temp = [{ 
     empDesc: c.empDesc, 
     empId: c.empId 
     }] 
     this.companies.push(temp); 
    }; 
    console.log("Companies",this.companies); 
} 
相關問題