2016-09-27 157 views
2

我想将我的类对象复制到临时对象。Angular-2:将一个对象复制到另一个对象

类属性:

export class PageModel {  
    AppID: any = null; 
    ParentID: any = null; 
    Type: any = null; 
    Order: any = null; 
    IsEnabled: boolean = false; 
    View: any = null; 
    Toolbars: any = null; 
    Attachments: any = null; 
} 

我最初的目标:

pageModel : PageModel =new PageModel(); 
pageModel.Type='New'; 
pageModel.Order=1; 

现在,我想这个更新的对象分配给任何临时对象,这个临时对象将指定为模式中的一种形式为,因此只能在保存按钮上单击我wan ts来更新我的主要对象。

我只需要帮助,如何将主对象复制到临时对象。

+1

怎么样'对象。分配()'? –

+0

它支持双向绑定,如果我改变在临时模型也影响主要一个 –

+0

我想念{}作为参数在Object.assign() –

回答

3
tempObject = Object.assign({}, tempObject, pageModel); 

这将创建一个新对象,将tempObject的所有属性赋值给它,然后将pageModel的所有属性赋值给它。

+0

谢谢,它的工作原理 –

+0

如果我有上面的单个对象它工作完美,但在对象列表的情况下,Object.assign不起作用,你有什么想法吗? –

+0

尝试'tempList = Object.assign([],tempList,pageModels);' –

0

亚历山大的答案是完美的这个问题。但有些情况下它不能正常工作,如

{ a: 0 , b: { c: 0}};

所以你可以使用,它也为深克隆工作

tempObject = JSON.parse(JSON.stringify(pageModel)); 

请参见波纹管例如:

let obj1 = { a: 0 , b: { c: 0}}; 
    let obj2 = Object.assign({}, obj1); 
    console.log(JSON.stringify(obj2)); // { a: 0, b: { c: 0}} 

    obj1.a = 1; 
    console.log(JSON.stringify(obj1)); // { a: 1, b: { c: 0}} 
    console.log(JSON.stringify(obj2)); // { a: 0, b: { c: 0}} 

    obj2.a = 2; 
    console.log(JSON.stringify(obj1)); // { a: 1, b: { c: 0}} 
    console.log(JSON.stringify(obj2)); // { a: 2, b: { c: 0}} 

    obj2.b.c = 3; 
    console.log(JSON.stringify(obj1)); // { a: 1, b: { c: 3}} 
    console.log(JSON.stringify(obj2)); // { a: 2, b: { c: 3}} 

    // Deep Clone 
    obj1 = { a: 0 , b: { c: 0}}; 
    let obj3 = JSON.parse(JSON.stringify(obj1)); 
    obj1.a = 4; 
    obj1.b.c = 4; 
    console.log(JSON.stringify(obj3)); // { a: 0, b: { c: 0}} 

更多信息,请访问该link

相关问题