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

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

问题描述

我需要一些关于服务和组件属性之间的绑定以及在角度2中的数据绑定的澄清。

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

  export class Service {
name =Luke;
object = {id:1};
getName(){return this.name};
getObject(){return this.object};
}

export class组件实现OnInit {
name:string;
对象:any;
constructor(private _service:Service){}
ngOnInit():any {

//这是2路绑定吗?
this.name = this._service.name;
this.object = this._service.object;

//这个复制?
this.name = this._service.getName();
this.object = this._service.getObject();
}
}


解决方案

您通过引用更新元素(如果您更新某些内容到对象属性),您将在视图中看到更新:

  export class Service {
(...)

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

如果您通过值更新元素(如果您更新某些内容进入名称属性),您将不会在视图中看到更新:

  export class Service {
(...)

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

看到这个plunkr: https://plnkr.co/edit/w7bS0fAVjOc3utnpD39b?p=preview


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();
  }
}

解决方案

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;
  }
}

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';
  }
}

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

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

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