Angular2 data binding between service and component properties

I need to clarify the binding between service and component properties and data binding in angular2

Suppose 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(); } } 
+5
source share
3 answers

If you update elements by reference (if you update something in 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 in the name property), you will not see updates in the view:

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

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

+5
source

Angular bindings only work for bindings declared in a view (HTML).

If you want the properties in your component to be updated when the values ​​in the service change, you need to take care of this yourself.

Observations make this easy. See nested property change detection for component input for an example.

+6
source

If you want the properties in the component to be updated as soon as the change value in the service changes:

  • Import DoCheck from @angular/core and your service into the component.
  • Call service functions that affect the component property in ngDoCheck(){...}
  • The component view is automatically updated immediately after any changes.

Something like this in your component:

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

Source: https://habr.com/ru/post/1246531/


All Articles