如何避免订阅过多?
是否有一个可用于确保取消任何活动订阅的功能?
clickDown(e) {
this.mouseMoveSubscription = fromEvent(this.elementRef.nativeElement, 'mousemove')
.subscribe((e: MouseEvent) => {
console.log(e);
});
}
答案 0 :(得分:2)
假设您没有使用async
管道,那么当前接受的模式是使用takeUntil
或takeWhile
来管理您的订阅onDestroy
。
例如:
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { takeWhile } from 'rxjs/operators';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
})
export class AppComponent implements OnInit, OnDestroy {
unsubscribed = false; // <-- When the component loads, subscriptions are all active.
constructor(private router: Router) { }
ngOnInit(): void {
this.router.events
.pipe(takeWhile(() => !this.unsubscribed)) // <-- Maintain this subscription while the component is not destroyed.
.subscribe(() => {});
}
ngOnDestroy(): void {
this.unsubscribed = true; // <-- When the component is destroyed, unsubscribe all subscriptions bound to this.unsubscribed.
}
}
答案 1 :(得分:1)
取消先前的订阅,如果成功,则再次订阅:
clickDown(e) {
if(this.mouseMoveSubscription) this.mouseMoveSubscription.unsubscribe();
this.mouseMoveSubscription = fromEvent(this.elementRef.nativeElement, 'mousemove')
.subscribe((e: MouseEvent) => {
console.log(e);
});
}
此外,在组件销毁时退订:
ngOnDestroy(): void {
if(this.mouseMoveSubscription) this.mouseMoveSubscription.unsubscribe();
}
答案 2 :(得分:1)
另一种选择是不手动订阅可观察的。
在任何地方添加clickDown(e) {
this.mouseMove$ = fromEvent(this.elementRef.nativeElement, 'mousemove');
}
都会使您感到疲倦,但这是因为这是不良做法
您可以使用Angular提供的async
管道。
该管道将订阅您的数据,并在组件被销毁时取消订阅。
在组件中不订阅
<div *ngIf="mouseMove$ | async as mouseMove">{{mouseMove}}</div>
在模板中使用browser.sendChromiumCommand('Page.setDownloadBehavior', {
'behavior': 'allow',
'downloadPath': downloadsPath
});
v10.15.1
答案 3 :(得分:0)
更好的方法是只在组件内部使用异步管道,为什么?
markForCheck()
功能来进行更改检测,因此您可以轻松地将组件移至onPush
策略