Reputation: 8519
So I recently posted angular2 data binding between service and component properties and Thierry pointed out something interesting.
If I have a reference datatype like an array or an object stored in a service (singelton) and create references in various components pointing to it, the view will update for all components when the object is updated from anywhere (and it works!).
In my case, I'm building a small forum where thread objects will need to be displayed/viewed in various components at the same time(e.g. preview, mainview, dashboard...). For updating/editing text fields this might come really handy.
Now i'm wondering if this is save to use?
Upvotes: 0
Views: 568
Reputation: 202316
You need to leverage observables on which components will subscribe to be notified when fields have changed.
Something like that:
export class Service {
name = "Luke";
nameUpdated = new Subject();
getName() {
return this.name;
}
updateName() {
this.name = 'Luke1';
this.nameUpdated.next(this.name);
}
}
and in the component:
this.name = this._service.name;
this._service.nameUpdated.subscribe(name => {
this.name = name;
});
See this plunkr: https://plnkr.co/edit/CRE92tdCsteoS2MVeGfh?p=preview
Upvotes: 0