在Angular 2/4/5中,$ watch和$ watchCollection等效吗?

时间:2018-09-05 10:21:13

标签: angular

你好StackOverflowers

我是Angular 2+的新手。在倾斜时,我找不到$ watch和$ watchCollection的等效项。

目标是在服务中存储的数据(数组或对象)更新时通知控制器。

2 个答案:

答案 0 :(得分:1)

在Angular 2+中,您应该订阅事件,而不是连续检查更改。看看我的以下示例,其中我订阅了对字符串的更改:

import { Injectable, Component, OnInit, OnDestroy } from '@angular/core';
import { Observable } from 'rxjs/internal/Observable';
import { Subject } from 'rxjs/internal/Subject';
import { Subscription } from 'rxjs/internal/Subscription';

@Injectable()
export class ExampleService {
  private exampleSubject = new Subject<string>();

  constructor() {
    setTimeout(() => {
      this.updateValue('hello');
    }, 5000);
  }

  updateValue(value: string): void {
    this.exampleSubject.next(value);
  }

  getValue(): Observable<string> {
    return this.exampleSubject.asObservable();
  }
}

@Component({
  selector: 'app-example',
  template: '<p>{{value}}</p>'
})
export class ExampleComponent implements OnInit, OnDestroy {
  private valueSubscription: Subscription;
  public value: string;

  constructor(private exampleService: ExampleService) { }

  ngOnInit() {
    this.valueSubscription = this.exampleService.getValue()
      .subscribe((val: string) => {
        this.value = val;
      });
  }

  ngOnDestroy() {
    this.valueSubscription.unsubscribe();
  }

}

创建组件后,它将运行ngOnInit,它将开始订阅更改(例如AngularJS中的$ watch)。 5秒钟后,服务将通过发出更改来更新值,该更改最终将在组件的预订部分中。完成操作后,别忘了退订该事件,以避免讨厌的内存泄漏和错误。

答案 1 :(得分:0)

您可以使用 DoCheck

import { Component, DoCheck } from '@angular/core';

要检测 changes 中是否存在通过引用传递的变量(例如数组),而 ngOnChanges() 未将其检测为旧值和新值值具有相同的引用