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");
}
});
}
I have the code above (or equivalent) in an angular 9 component. When I move back and forth in the application, coming to the component again and again using forward and back navigation, I notice that the subscriptions to router.events
keep mounting up... Yet there is no way to unsubscribe from the router.events
for instance inside of ngOnDestroy... How can I achieve a singleton event subscription in this case?
An Observable doesn't have an unsubscribe
method but a Subscription does
. When you call .subscribe
on an Observable, it returns a Subscription
object. This is what we use to unsubscribe from our 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
}
}
}
Above is a simple example. Hope this helps
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.