How to auomatically subscribe and unsubscribe an Observable in Angular
There are several ways to unsubscribe the Observable
in Angular but best way to unsubscribe is using async
pipe.
The async
pipe subscribes to an Observable
or Promise
and returns the latest value it has emitted. When the component gets destroyed, the async
pipe unsubscribes automatically to avoid potential memory leaks.
@Component({
template: `
<div>
Interval: {{observable$ | async}}
</div>
`
})
export class AppComponent implements OnInit {
observable$
ngOnInit () {
this.observable$ = Rx.Observable.interval(1000);
}
}