This library provides utility methods which help to unsubscribe from ReactiveX's Observables in Angular applications.
Why?
Failing to unsubscribe from observables will lead to unwanted memory leaks as the observable stream is left open, potentially even after a component has been destroyed or the user has navigated to another page.
Important: If services are used in Hierarchical Dependency Injectors they are affected by the same memory-leak issue!
This blog post provides additional information:
Patrons
❤️ theCodeCampus - Trainings for Angular and TypeScript
Requirements
- Requires >= RxJS 6.0.0 (part of Angular 6)
@Component({
selector: 'foo',
templateUrl: './foo.component.html'
})
export class FooComponent implements OnInit, OnDestroy {
ngOnInit() {
interval(1000)
.pipe(
untilComponentDestroyed(this) // <--- magic is here!
)
.subscribe();
}
ngOnDestroy() {
}
}
Download the NPM package
npm i --save @w11k/ngx-componentdestroyed
Prepare the class
The class must have a ngOnDestroy()
method (it can be empty):
@Component({
selector: 'foo',
templateUrl: './foo.component.html'
})
export class FooComponent implements OnDestroy {
// ...
ngOnDestroy() {
}
}
Either use
untilComponentDestroyed(this)
takeUntil(componentDestroyed(this))
as the last Observable pipe operator. The TypeScript compiler will ensure that this
' class implements a ngOnDestroy()
method.
import {interval} from "rxjs";
import {takeUntil} from "rxjs/operators";
import {componentDestroyed} from "@w11k/ngx-componentdestroyed";
interval(1000)
.pipe(
untilComponentDestroyed(this)
)
.subscribe();
Our sister project @w11k/rx-ninja provides a TSLint rule to enforce the use a terminator operator. If you want to use untilComponentDestroyed(this)
instead of takeUntil(componentDestroyed(this))
please add this configuration:
{
"rulesDirectory": [
"node_modules/@w11k/rx-ninja/dist/tslint_rules"
],
"rules": {
"rx-ninja-subscribe-takeuntil": [true, "takeUntil", "untilComponentDestroyed"]
}
}