Rule Definition
onDestroy is the place to free resources that won't be garbage-collected automatically.
You risk memory leaks if you neglect to unsubscribe from Observables and DOM events.
Remediation
Ensure you cleanup just before Angular destroys the directive or component, unsubscribe Observables to avoid memory leaks
Violation Code Sample
import { Component } from '@angular/core';
import { AuthService } from './auth.service';
@Component({...})
export class ShowUserComponent {
constructor(private authService: AuthService) {}
showLoggedInUser() {
this.authService
.getLoggedInUserName()
.subscribe(username => window.alert(`You are logged in as ${username}!`));
}
// VIOLATION
}
Fixed Code Sample
import { Component, OnDestroy } from '@angular/core';
import { AuthService } from './auth.service';
import { Subscription } from 'rxjs';
@Component({...})
export class ShowUserComponent implements OnDestroy {
myUserSub: Subscription;
constructor(private authService: AuthService) {}
showLoggedInUser() {
this.myUserSub = this.authService
.getLoggedInUserName()
.subscribe(username => window.alert(`You are logged in as ${username}!`));
}
ngOnDestroy() {
if (this.myUserSub) {
this.myUserSub.unsubscribe();
}
}
}
Reference
https://cwe.mitre.org/data/definitions/404.html
https://angular.io/guide/lifecycle-hooks#ondestroy
Related Technologies
Technical Criterion
CWE-772 - Missing Release of Resource after Effective Lifetime
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.