I've read that normally you don't have to unsubscribe from Router
or ActivatedRoute
explicitly because:
The ActivatedRoute and its observables are insulated from the Router itself. The Router destroys a routed component when it is no longer needed and the injected ActivatedRoute dies with it.
source: Do I have to unsubscribe from ActivatedRoute (e.g. params) observables?
However I am calling subscribe()
on ActivatedRoute.firstChild.paramMap
repeatedly in the parent component app.component
. This component is only destroyed when the user navigates away from the web application or closes the website so i'm worried that those paramMap
subscriptions might remain active the entire time.
The subscription calls are made within a Router.events
subscription and it looks like this:
this.routerSubscription = this.router.events
.pipe(
tap((event) => {
switch (true) {
case event instanceof NavigationStart: {
setTimeout(() => this.showChildComponentLoading = true);
break;
}
case event instanceof NavigationEnd:{
this.activatedRoute.firstChild.paramMap.subscribe(paramMap => {
if(paramMap.has('mode')){
let newWebAppMode:string = paramMap.get('mode');
if(this.dataStoreService.isValidWebAppMode(newWebAppMode) && newWebAppMode !== this.dataStoreService.currentAppMode)
this.saveToLocalStorage.next([DataType.WEB_APP_MODE, newWebAppMode]);
}
});
//other code
Every time someone navigates to another component/page activatedRoute.firstChild.paramMap
is subscribed to again. I have to do this inside the router subscription and only when the event is an instance of NavigationEnd
because before that the url parameters are not yet available.
My question is, what happens to those subscriptions? Do they unsubscribe automatically or do i need to unsubscribe each new one manually? If the latter is the case, how can i do that effectively?
Some of you may advice me to use activatedRoute.firstChild.snapshot.paramMap.myParameter
because then i don't have to subscribe to anything. However, snapshot
does not work when the url parameter changes while the same component is reused. So i can't use that.
Thank you