angular2 data binding between service and component properties

Han Che picture Han Che · Apr 6, 2016 · Viewed 11k times · Source

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

Answer

Günter Zöchbauer picture Günter Zöchbauer · Apr 6, 2016

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.