服务和组件属性之间的 angular2 数据绑定 [英] angular2 data binding between service and component properties

查看:38
本文介绍了服务和组件属性之间的 angular2 数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要澄清一下 angular2 中服务和组件属性之间的绑定以及数据绑定

I need some clarification on binding between service and component properties and data binding in angular2

假设我有一个服务(单例)和一个组件

assume i have a service(singleton) and a component

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 属性中),您将在视图中看到更新:

If you update elements by reference (if you update something into the object property), you will see the updates in the view:

export class Service {
  (...)

  updateObject() {
    this.object.id = 2;
  }
}

如果您按值更新元素(如果您将某些内容更新到 name 属性中),您将不会在视图中看到更新:

If you update elements by value (if you update something into the name property), you won't see the updates in the view:

export class Service {
  (...)

  updateName() {
    this.name = 'Luke1';
  }
}

查看此 plunkr:https://plnkr.co/edit/w7bS0fAVjOc3utnpD39b?p=preview.

See this plunkr: https://plnkr.co/edit/w7bS0fAVjOc3utnpD39b?p=preview.

这篇关于服务和组件属性之间的 angular2 数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆