Router - Clarify params subscription behavior when deactivating a route
See original GitHub issue[ x ] bug report
Current behavior This is a quote from the official documentation -
The subscriptions are cleaned up when the component is destroyed, protecting against memory leaks, so you don’t need to unsubscribe from the route params Observable.
The subscription is still active.
Expected behavior Angular should unsubscribe from the params observable when the component destroyed. ( or change the documentation )
Minimal reproduction of the problem with instructions
You can test this behavior with the delay operator.
@Component({
...
})
export class TestComponent implements OnInit {
params;
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.params = this.route.params.delay(3000).subscribe(console.log);
}
}
When navigates to a different route the handler is still running.
You can verify this by calling explicitly to the unsubscribe() method.
ngOnDestroy() {
this.params.unsubscribe();
}
Now you will see that the handler is not running.
Angular version: 4.0.X
Issue Analytics
- State:
- Created 6 years ago
- Reactions:43
- Comments:22 (3 by maintainers)
Top Results From Across the Web
Do I have to unsubscribe from ActivatedRoute (e.g. params ...
No need to unsubscribe any router params. You will only need unsubscribe if you have created in component level. · Yes, you need,...
Read more >Angular Router: Revealing some interesting facts and ...
Exploring some handy features provided by Angular Router. ... Firstly, with a non-wildcard route we can reuse the query params and the ...
Read more >Testing Angular route guards with the RouterTestingModule
The first test case covers usage of the CanActivate route guard interface (3). It uses the dummyRoute parameter and the fakeRouterState factory ...
Read more >Implementing Routing Policy on Cisco IOS XR Software
A routing policy instructs the router to inspect routes, filter them, and potentially modify their attributes as they are accepted from a peer, ......
Read more >CanDeactivate
... a class can implement to be a guard deciding if a route can be deactivated. ... currentUser, route.params.id); } } @NgModule({ imports:...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found

I’m searching for a while for the best practices of unsubscribing from observables at Angular and I decided to share with you the result of my searches to review it if I miss something. I see that this issue is related and decided to comment here instead of creating a question issue.
Some of the best practices regarding observables unsubscriptions inside Angular components:
A quote from
Routing & NavigationAnd in responding to the following links:
httpobservableI collected some of the best practices regarding observables unsubscriptions inside Angular components to share with you:
Never unsubscribe from anhttpobservable as it isfiniteand it unsubscribes and cleans itself automatically (1), (2)httpobservable unsubscription is conditional and we should consider the effects of the ‘subscribe callback’ being run after the component is destroyed on a case by case basis. We know that angular unsubscribes and cleans thehttpobservable itself (1), (2). While this is true from the perspective of resources it only tells half the story. Let’s say we’re talking about directly callinghttpfrom within a component, and thehttpresponse took longer than needed so the user closed the component. Thesubscribe()handler will still be called even if the component is closed and destroyed. This can have unwanted side effects and in the worse scenarios leave the application state broken. It can also cause exceptions if the code in the callback tries to call something that has just been disposed of. However at the same time occasionally they are desired. Like, let’s say you’re creating an email client and you trigger a sound when the email is done sending - well you’d still want that to occur even if the component is closed (8).AsyncPipeas much as possible because it automatically unsubscribes from the observable on component destruction.ActivatedRouteobservables likeroute.paramsif they are subscribed inside a nested (Added inside tpl with the component selector) or dynamic component as they may be subscribed many times as long as the parent/host component exists. No need to unsubscribe from them in other scenarios as mentioned in the quote above fromRouting & Navigationdocs.Note: Regarding scoped services, i.e component providers, they are destroyed when the component is destroyed. In this case, if we subscribe to any observable inside this provider, we should consider unsubscribing from it using the
OnDestroylifecycle hook which will be called when the service is destroyed, according to the docs.takeUntil(3) or you can use thisnpmpackage mentioned at (4) The easiest way to unsubscribe from Observables in Angular.FormGroupobservables likeform.valueChangesandform.statusChangesRenderer2service likerenderer2.listenHostListeneras angular cares well about removing the event listeners if needed and prevents any potential memory leak due to event bindings.A nice final tip: If you don’t know if an observable is being automatically unsubscribed/completed or not, add a
completecallback tosubscribe(...)and check if it gets called when the component is destroyed.My understanding of this is that the source params/data/etc observables are garbage collected when the component and its injector with the
ActivatedRoutegets garbage collected. No wording aboutunsubscribeor any cleanup. It seems, that a delayedObservablestill holds an active reference for a timeout callback or subscriber (??? I’m not aware about the internals) preventing it from garbage collection. After the timeout fires (or in real scenarios the HTTP returns), theObservabledies. Anyway I don’t see this as a memory leak, rather just a specific case what should be handled manually. But true, this should be well documented, since some HTTP call should be also cancelled to prevent from some side effects and save some resources.Can someone confirm my assumptions?