[英]How Can I Achieve a Singleton Subscription To router.events in Angular 9
constructor(
private route: ActivatedRoute,
private router: Router,
private viewportScroller: ViewportScroller
) {
this.router.events
.pipe(filter((e): e is Scroll => e instanceof Scroll))
.subscribe((e) => {
if (e.position) {
console.log("// position navigation", e.position);
this.viewportScroller.scrollToPosition(e.position);
} else if (e.anchor) {
console.log("// anchor navigation", e.anchor);
this.viewportScroller.scrollToAnchor(e.anchor);
} else {
console.log("// forward navigation");
}
});
}
我在 angular 9 組件中有上述代碼(或等效代碼)。 當我在應用程序中來回移動,使用前進和后退導航一次又一次地來到組件時,我注意到對router.events
的訂閱不斷增加......但是沒有辦法取消對router.events
的訂閱例如在 ngOnDestroy 內部......在這種情況下,如何實現 singleton 事件訂閱?
Observable 沒有unsubscribe
方法,但Subscription does
。 當你在 Observable 上調用.subscribe
時,它會返回一個Subscription
object。 這是我們用來取消訂閱我們的 Observables 的。
export class YourComponent implements OnDestroy {
routerSubscription: Subscription;
constructor(
private route: ActivatedRoute,
private router: Router,
private viewportScroller: ViewportScroller
) {
this.routerSubscription = this.router.events
.pipe(filter((e): e is Scroll => e instanceof Scroll))
.subscribe((e) => {
if (e.position) {
console.log("// position navigation", e.position);
this.viewportScroller.scrollToPosition(e.position);
} else if (e.anchor) {
console.log("// anchor navigation", e.anchor);
this.viewportScroller.scrollToAnchor(e.anchor);
} else {
console.log("// forward navigation");
}
});
}
ngOnDestroy() {
if (this.routerSubscription) {
this.routerSubscription.unsubscribe();
this.routerSubscription = undefined; // just in case. If this.routerSubscription is undefined, calling .unsubscribe() on it will throw an error and halt your component
}
}
}
上面是一個簡單的例子。 希望這可以幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.