When you subscribe to query params in a component, do you need to unsubscribe? I'm trying to avoid a memory leak.
Subscription with variable for unsubscribe()
subscription$: Subscription
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.subscription$ = this.route.queryParams.subscribe(
(params: any): void => {
// ... Do stuff here ...
}
)
}
ngOnDestroy() {
if (this.subscription$ !== undefined || this.subscription$ !== null) {
this.subscription$.unsubscribe()
}
}
Subscription without variable for unsubscribe()
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route.queryParams.subscribe(
(params: any): void => {
// ... Do stuff here ...
}
)
}
Which one is a better solution?
queryparams
is deprecated, you shouldn't be using this Two older properties are still available, however, their replacements are preferable as they may be deprecated in a future Angular version. – LiamActivatedRoute
is nulled out when the route is destroyed, so there is no need to manually unsubscribe. – Andrei Gătej