Observables have the subscribe method we call with a callback function to get the values emitted into the Observable aloso we can unsubscribe from Observables. In Angular, we use it in Components/Directives especially in the router module, NgRx, HTTP module.

Before closing a component , we must unsubscribe from all the existing observables . Of cores the observable have a unsubscribe method that we call in the ngOnDestroy() witch is a part of the lifecycle of the component to cancel the executions

Example :

@Component({...})
export class AppComponent implements OnInit, OnDestroy {
    subscription: Subscription 
    ngOnInit () {
        var observable = Rx.Observable.interval(1000);
        this.subscription = observable.subscribe(x => console.log(x));
    }
    ngOnDestroy() {
        this.subscription.unsubscribe()
    }
}

Laisser un commentaire