[英]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.