我需要澄清服务和组件属性之间的绑定以及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'; } }
看到这个plunkr:https://plnkr.co/edit/w7bS0fAVjOc3utnpD39b?p=preview.