gpt4 book ai didi

Angular 2 RC 5 - Observable.interval 触发变化检测

转载 作者:太空狗 更新时间:2023-10-29 18:02:16 24 4
gpt4 key购买 nike

我在组件树的某处创建了一个 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();
}
}
}

最佳答案

您可以使用 ChangeDetectionStrategy.OnPush 为组件关闭它。

每个事件都会导致更改检测运行(和 setTimeout,以及 NgZone 涵盖的任何其他异步 API)。

如果您使用 OnPush,则仅更改来自使用 订阅的可观察对象的输入和事件 | async 引起变化检测。

关于Angular 2 RC 5 - Observable.interval 触发变化检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39290028/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com