I find many examples where ActivatedRoute
Observables like params
or url
are subscribed but not unsubscribed.
constructor(private route: ActivatedRoute) {} ngOnInit() { this.route.params // (+) converts string 'id' to a number .switchMap((params: Params) => this.service.getHero(+params['id'])) .subscribe((hero: Hero) => this.hero = hero); }
Observable
s?Router
.routerState
?No. From the docs : When subscribing to an observable in a component, you almost always arrange to unsubscribe when the component is destroyed. There are a few exceptional observables where this is not necessary.
In Angular applications, it's always recommended to unsubscribe the observables to gain benefits like: Avoids Memory Leaks. Aborting HTTP requests to avoid unwanted calls.
As you probably know when you subscribe to an observable or event in JavaScript, you usually need to unsubscribe at a certain point to release memory in the system. Otherwise, you will have a memory leak. A memory leak occurs when a section of memory that is no longer being…
Specifically, we must unsubscribe before Angular destroys the component. Failure to do so could create a memory leak. We unsubscribe from our Observable in the ngOnDestroy method.
From the docs :
When subscribing to an observable in a component, you almost always arrange to unsubscribe when the component is destroyed.
There are a few exceptional observables where this is not necessary. The ActivatedRoute observables are among the exceptions.
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.
Feel free to unsubscribe anyway. It is harmless and never a bad practice.
As the winning answer quotes about the subscriptions
to ActivatedRoute
, Angular unsubscribes
automatically.
The Router destroys a routed component when it is no longer needed and the injected ActivatedRoute dies with it.
In case you want to know how to unsubscribe
from Observables
:
import { Component, OnInit, OnDestroy } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; // Type import { Subscription } from 'rxjs/Subscription'; @Component({ selector: 'app-example', templateUrl: './example.component.html', styleUrls: ['./example.component.scss'] }) export class ExampleComponent implements OnInit, OnDestroy { paramsSubscription : Subscription; constructor(private activatedRoute : ActivatedRoute) { } /* Angular lifecycle hooks */ ngOnInit() { console.log("Component initialized"); this.paramsSubscription = this.activatedRoute.params.subscribe( params => { }); } ngOnDestroy() { console.log("Component will be destroyed"); this.paramsSubscription.unsubscribe(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With