Currently, in our app we are using location.reload as a sure way to clear all observables of any previous data.
Is there any other less hacky way of doing this like without reloading the whole app or some rxjs recommended way?
CodePudding user response:
The correct way to handle observables in an angular application is to unsubscribe when they are no more needed.
Generally speaking we subscribe to an Observable inside a component. So when you destroy the component you must unsubscribe the subscription as follow:
class MyComponent implements OnInit, OnDestroy {
// Variable used to hold subscription
private subscription: Subscription;
ngOnInit() {
// Save subscription in a variable
this.subscription = anyObservable.subscribe(...);
}
ngOnDestroy() {
// Unsubscribe when the subscription is no more needed
this.subscription.unsubscribe();
}
...
}
There can be are observables that survive through the whole application lifetime, while others must be unsubscribed as soon as possible, but often subscribing on the onInit and unsubscribing on the onDestroy methods is a good approach to solve most of the problems.
CodePudding user response:
try to unsubscribe the subscribed observable, Once there responsibility has been completed.