In Angular, unsubscribe from observables to prevent memory leaks by:
1. Manual Unsubscribe:
subscription: Subscription;
ngOnInit() {
this.subscription = this.myService.getData().subscribe(data => { /* ... */ });
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
2. Using takeUntil:
destroy$ = new Subject<void>();
ngOnInit() {
this.myService.getData()
.pipe(takeUntil(this.destroy$))
.subscribe(data => { /* ... */ });
}
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
3. Using async pipe (auto-unsubscribes):
<div *ngIf="data$ | async as data">{{ data }}</div>