Alexander Shirobokov2016-05-20 11:32:33
Alexander Shirobokov, 2016-05-20 11:32:33

Angular2. How to catch changes in an object?

There is an object:
var a = {foo: 1};
and somewhere it was changed to:
a.foo = 'new value';
How do you know that the object has been changed (preferably by a callback)?
Angular has RxJs for this purpose with its own Observable, but I don't know how to use it to detect changes in an object.
I found this solution in the open spaces:
but the funny thing is that there is no


is there

which does not respond to changes.
How to decide?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
_ _, 2016-05-20

creates a stream that contains one event with value. It's not about change at all.
From the template you want to apply, in Angular2 they go towards reactivity.
Components in Angular2 have input properties whose changes can be tracked using a life-cycle callback, specifically the OnChanges interface. It will look something like this:

@Component({selector: 'my-component', template: '<span>{{text}}</span>'}}
class MyComponent implements OnChanges {
  public text: string;
  @Input() changeMe: string;
  ngOnChanges(changes) {
    this.text = Date.now().toString();

Let's say in your top level component you have:
Изменяя someValue вы изменяете input-атрибут changeMe компонента MyComponent. При каждом изменении будет срабатывать ngOnChanges.
Еще одно замечание - если в качестве значения вы передаете объект, то не надо его мутировать. Создавайте новый объект и присваивайте заново.
this.someValue = {value: 1, anotherValue: 2};
this.someValue = Object.assign({}, this.someValue, {value: 2}); // {value: 2, anotherValue: 2} // Но тут this.someValue это ссылка уже на другой объект.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question