简体   繁体   English

服务和组件属性之间的angular2数据绑定

[英]angular2 data binding between service and component properties

I need some clarification on binding between service and component properties and data binding in angular2 我需要澄清服务和组件属性之间的绑定以及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();
  }
}

Angular binding only works for bindings declared in the view (HTML). Angular绑定仅适用于视图(HTML)中声明的绑定。

If you want properties in your component being updated when values in a service change, you need to take care of it yourself. 如果您希望在服务中的值发生更改时更新组件中的属性,则需要自己处理。

Observables make this easy. Observables使这很容易。 See detect change of nested property for component input for an example. 有关示例,请参阅检测组件输入的嵌套属性的更改

If you update elements by reference (if you update something into the object property), you will see the updates in the view: 如果通过引用更新元素(如果将某些内容更新到object属性中),您将在视图中看到更新:

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: 如果按值更新元素(如果将某些内容更新到name属性中),则不会在视图中看到更新:

export class Service {
  (...)

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

See this plunkr: https://plnkr.co/edit/w7bS0fAVjOc3utnpD39b?p=preview . 请参阅此plunkr: https ://plnkr.co/edit/w7bS0fAVjOc3utnpD39b p = preview。

If you want properties in a component updates as soon as a value in change in a service changes: 如果您希望在服务更改中的值发生更改时更新组件中的属性:

  1. Import DoCheck from @angular/core and your service into the component. @angular/core和您的service DoCheck导入组件。
  2. Call the service functions affecting the component property in ngDoCheck(){...} ngDoCheck(){...}调用影响组件属性的服务函数
  3. The component view will be updated automatically as soon as any changes 一旦发生任何更改,组件视图将自动更新

Something like this in your component: 你的组件中有这样的东西:

  ngDoCheck() {
    this.qty = this.cartService.getTotalQtyInCart();
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM