2017-05-16 35 views
0

希望有人能帮助我理解Angular中的这种行为。角度数据绑定 - 服务中的数据更改

存在使用ngmodel双向数据结合结合到组件变量一个简单的输入。组件初始化时,使用dataService检索数据,该数据服务返回可正常工作的员工对象。但是,当我编辑输入框中的值时,组件变量员工的名称发生更改,而且服务中的数据也发生了改变,这对我来说非常奇怪。从服务返回的数据不应该受到影响吗?在下面找到plunker。

请参阅本plunker https://plnkr.co/edit/wjuJLo?p=preview

getData() { 
    console.log(this.employee); 
    console.log(this.service.getEmp()); 
    } 

感谢和问候, 阿什利

回答

2

问题在于这部分代码。

ngOnInit() { 
     this.employee = this.service.getEmp(); 
     } 

在JavaScript中,变量只包含对象的引用,而不包含对象本身。因此this.employee必须this.service.getEmp();

的引用,因此只要更改this.employee,它会在参考更改值,因此你会从服务中获得的价值将是一个更新的,而不是你所期望的一个。

中序克隆,

使用jQuery check this answer for more info

// Shallow copy 
this.employee = jQuery.extend({}, this.service.getEmp()); 

// Deep copy 
this.employee = jQuery.extend(true, {}, this.service.getEmp()); 

或者使用Object.assign

this.employee = Object.assign({}, this.service.getEmp());

或者使用Lodash

this.employee = _.clone(this.service.getEmp()); 
1

要分配getEmp()来this.employee意味着你分配getEmp() reference to this.empoyee所以如果你改变什么this.employee那么这也会反映到getEmp()。

在这里,你必须确保你将make a copy of getEmp()分配给this.employee之前。这将解决您的问题。

解决方案的代码附加以下

export class App implements OnInit { 
    private employee: Employee = new Employee(); 
    constructor(private service: dataService) { 

    } 

    ngOnInit() { 
    this.employee = Object.assign({}, this.service.getEmp()); // making copy of getEmp() 
    } 

    getData() { 
    console.log(this.employee); 
    console.log(this.service.getEmp()); 
    } 
} 

干杯!

+0

嗨。谢谢回复。这是标准的方法吗? – ashley