0

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?

Community
  • 1
  • 1
Han Che
  • 8,239
  • 19
  • 70
  • 116
  • If your text field values are also stored in objects (hence stored in reference types), then yes, it is safe to use. If you want to use primitive types, see Thierry's answer. The cookbook also has an example of using a Subject: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service – Mark Rajcok Apr 06 '16 at 15:37

1 Answers1

0

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

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • what you've added now is a way to get the view updated for changes of primitives datatypes in the service right? (i guess new Subject is an observable?). In any case thanks for the help! – Han Che Apr 06 '16 at 14:26
  • In fact your component is now notified of updates in the service and can update the properties the view is bound on accordingly. Yes the subject class inherits both Observable and Observer... You're welcome! – Thierry Templier Apr 06 '16 at 14:30
  • I definetly need to learn more about observables but so far mostly you can find is about rxJS and HTTP, do you have any tip on where to start? – Han Che Apr 06 '16 at 14:57