K
K
kodwi2017-03-30 10:31:40
Angular
kodwi, 2017-03-30 10:31:40

What are the ways to track the change of an object in Angular 2 (analogues of $watch)?

There is a common service with data in it. It is connected to different components. When you change the object of this service in one component, you need to catch these changes in another. Angular 1 has $watch, and I believe there is a $watch in Angular 2. Maybe somehow through RxJS?
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
kodwi, 2017-03-30
@kodwi

Found the answer. Reactive programming. The entity Rx.Subject is needed.
Below is an example on type script.

class SomeService {
  info: any = {}; // хотим отслеживать это поле
  infoSubject: Rx.Subject = new Rx.Subject();

  infoChanged(): Rx.Subject {
    return this.infoSubject;
  }

  addInfo(): void {
    this.info.blabla = '123';
    this.infoSubject.next(); // этот метод вызывает все подписанные на этот subject колбэки
  }
}

class AnotherService {
  constructor(private _someService: SomeService) {
    // подписываемся на изменения info из SomeService
    this._someService.infoChanged().subscribe({
      next: () => console.log('Object info from SomeService has changed!')
    });
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question