angular2 data binding between service and component properties

怎甘沉沦 提交于 2019-12-07 02:48:36

问题


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

回答1:


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.




回答2:


Angular binding only works for bindings declared in the view (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. See detect change of nested property for component input for an example.




回答3:


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.
  2. Call the service functions affecting the component property in 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();
  }


来源:https://stackoverflow.com/questions/36446330/angular2-data-binding-between-service-and-component-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!