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?

1
  • 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: angular.io/docs/ts/latest/cookbook/… Commented Apr 6, 2016 at 15:37

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

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!
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!
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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.