我在组件树的某个地方创建了一个 500 毫秒的 Observable.interval 并订阅了它。该组件没有输入或输出属性。每次发送一个滴答声时,该间隔都会从根组件开始触发更改检测。这会在我的应用程序中造成大量不必要的开销。我没有找到有关该行为的任何文档。
是否可以关闭由这个 Observable 引起的变化检测?
编辑:添加代码
下面的代码演示了我想要做什么。我按照 Günter 的建议将间隔放在 Angular 区域之外,但现在对数组的修改不会在模板中发布。有没有办法在不触发更改检测的情况下更新模板?
import {NotificationList} from "./NotificationList";
import {Notification} from "./Notification";
import {Component, OnDestroy, ChangeDetectorRef, NgZone} from "@angular/core";
import { Subscription } from 'rxjs/Subscription';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/interval';
class TimedNotification {
notification: Notification;
remainingTime: number;
}
@Component({
selector: "notifications",
template: `
<ul>
<li *ngFor="let notification of notifications">notification.message</li>
</ul>
`
})
export class NotificationComponent implements OnDestroy {
notifications: Array<TimedNotification> = [];
private subscription: Subscription;
private timer: Subscription = null;
private delay: number = 2000;
private tickDelay: number = 500;
constructor(notificationQueue: NotificationList, private zone: NgZone) {
this.subscription = notificationQueue.getObservable().subscribe(notification => this.onNotification(notification));
this.zone.runOutsideAngular(() => {this.timer = Observable.interval(500).subscribe(x => this.onTimer())});
}
private onTimer(): void {
if(this.notifications.length == 0) {
return;
}
let remainingNotifications: Array<TimedNotification> = [];
for(let index in this.notifications) {
let timedNotification = this.notifications[index];
timedNotification.remainingTime -= this.tickDelay;
if(timedNotification.remainingTime <= 0) {
continue;
}
remainingNotifications.push(timedNotification);
}
this.notifications = remainingNotifications;
}
private onNotification(notification: Notification): void {
let timedNotification = new TimedNotification();
timedNotification.notification = notification;
timedNotification.remainingTime = this.delay;
this.notifications.push(timedNotification);
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
if(this.timer !== null) {
this.timer.unsubscribe();
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用以下命令为组件关闭它ChangeDetectionStrategy.OnPush。
每个事件都会导致更改检测运行(并且setTimeoutNgZone 涵盖的任何其他异步 API)。
如果您使用OnPush,则仅对可观察量订阅的输入和事件进行更改,并进行| async原因更改检测。