Create observable from simple object

I am completely new to RxJS so apologize in advance if this has already been answered.

I have an Angular 2 app and in one of the components I have a simple object. I am binding an interface to this object. What I would like to do is be able to commit all changes to this object, regardless of whether they come from code or from a user modifying one of the fields.

I've looked at the observable, but it seems like subscribers can only receive notifications if a new one is introduced via the Emit method. How does this work in the case of a property associated with an input field, for example?

Is there a better way to do this?

This is what my code looks like:

export class MyComponent {
  app: ApplicationModel = new ApplicationModel(); <--- this is the object I want to track
  
  constructor(api: APIService) {
    api.getApplication().then((data) => {
      this.app = data; 
    });
  }
}
      

Run codeHide result


I'm looking for something similar to how Knockout allows change notifications:

myViewModel.personName.subscribe(function(newValue) {
    alert("The person new name is " + newValue);
});
      

Run codeHide result


Thank.

+3


source to share


1 answer


When using @Input

or just tracking changes from a service or even the same component, you can use BehaviorSubject

.

import { BehaviorSubject } from 'rxjs/BehaviorSubject';

appModel = new BehaviorSubject(new ApplicationModel());

      

Push new changes:

appModel.next(applicationModelModified);

      



Subscribe to new changes:

appModel.subscribe(val => ...)

      

Reading a value anywhere:

appModel.value

      

+2


source







All Articles