我需要对服务和组件属性之间的绑定以及 Angular2 中的数据绑定进行一些澄清
假设我有一个服务(单例)和一个组件
export class Service {
name = "Luke";
object = {id:1};
getName(){return this.name};
getObject(){return this.object};
}
export class Component implements OnInit{
name:string;
object:any;
constructor(private _service:Service){}
ngOnInit():any{
//Is this 2 way binding?
this.name = this._service.name;
this.object = this._service.object;
//Is this copying?
this.name = this._service.getName();
this.object = this._service.getObject();
}
}
如果您通过引用更新元素(如果您将某些内容更新到object
属性),您将在视图中看到更新:
export class Service {
(...)
updateObject() {
this.object.id = 2;
}
}
如果您按值更新元素(如果您将某些内容更新到name
属性),您将不会在视图中看到更新:
export class Service {
(...)
updateName() {
this.name = 'Luke1';
}
}
看看这个笨蛋:https://plnkr.co/edit/w7bS0fAVjOc3utnpD39b?p=preview https://plnkr.co/edit/w7bS0fAVjOc3utnpD39b?p=preview.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)