javascript / expert
Snippet
Explicit Resource Lifecycle Management with DestroyRef
DestroyRef, introduced in Angular 16, provides a functional alternative to the ngOnDestroy lifecycle hook. It allows developers to register cleanup logic directly within the scope where a resource is initialized, reducing the risk of memory leaks in services or functions that don't have a traditional lifecycle.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
@Injectable()export class WebSocketService {private destroyRef = inject(DestroyRef);connect(url: string) {const socket = new WebSocket(url);this.destroyRef.onDestroy(() => {socket.close();console.log('Socket cleaned up');});}}
angular
Breakdown
1
private destroyRef = inject(DestroyRef);
Retrieves the destruction reference for the current injection context (component, directive, or service).
2
this.destroyRef.onDestroy(() => {
Registers a callback function that will be executed automatically when the context is destroyed.