Ưu tiên async pipe trong template vì tự unsubscribe.
Khi phải subscribe trong class, dùng takeUntilDestroyed() với DestroyRef:
typescript
private destroyRef = inject(DestroyRef)
ngOnInit() {
this.router.events
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(event => this.trackNavigation(event))
}Không cần unsubscribe với HTTP Observable hoàn tất một lần, nhưng vẫn cần cẩn thận với streams dài như router events, form valueChanges, interval, WebSocket hoặc Subject từ service.
Prefer the async pipe in templates because it unsubscribes automatically.
When subscribing in a class, use takeUntilDestroyed() with DestroyRef:
typescript
private destroyRef = inject(DestroyRef)
ngOnInit() {
this.router.events
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(event => this.trackNavigation(event))
}One-shot HTTP Observables complete on their own, but long-lived streams such as router events, form valueChanges, intervals, WebSockets or service Subjects still need care.