I am performing a http call and subscribing to it. If I close that component, the subscription is not destroyed, and it runs once. Shouldn't the http subscriptions be removed automatically once I destroy a component?
Here's the method that is being called
getCubes() {
this.loading_cubes = true;
this.urlService.getCubes().subscribe({
next:(data:any) => {
if (data.success) {
this.cubesDataArray = data.data[0].response;
} else {
Swal.fire(data.status_message);
console.log(data.error_message);
}
this.loading_cubes = false;
},
error:(err:any) => {
console.log(err);
Swal.fire('Opps an error occured');
this.loading_cubes = false;
}
});
}
And here's the service function that's returning the http observable.
getCubes() {
return this.http.get(this.serviceURL '/cubes', this.options);
}
This is just an single case, It's happening with every req I make. The pop ups keep coming up even after I closed the component.
Also it it possible that it is some setting in the tsconfig.json?
CodePudding user response:
You'll have to hook into the onDestroy to remove your subscribertion:
export MyComponent extends OnDestroy {
mySubscription = null
...
getCubes() {
this.mySubscription = this.urlService.getCubes().subscribe({
...
});
}
ngOnDestroy() {
this.mySubscription.unsubscribe();
}
}
CodePudding user response:
Matthew provided you already good answer. There are also other options besides his anwer.
You can instruct RxJS to take only one result. Then code should be like:
this.urlService.getCubes().pipe(take(1)).subscribe({ ... });
This pipe(take(1))
is instructing to only take one result.
Second approach would be to convert observable to promise. This can be achieved with
firstValueFrom
function from RxJS. Then code should be like:firstValueFrom(this.urlService.getCubes()).then({ ... });
You may ask why HttpClient is behaving in this strange manner. Let me try to explain it a little bit.
HttpClient methods like get, put, post, delete etc. are returning so called cold observables
. The main idea of them is that they are not being executed if there is now consumer on the end. You can check what will happen if you don't do subscribe - nothing will happen, request will not be sent.
This allows you also to create one "halted request" and call it mutliple times - for example with multiple subscribe.
What would need that? Let's consider this code:
this.urlService.getCubes()
.pipe(retry(3))
.subscribe({
...
});
Here I have used retry
operator. What it does is catching error and redoing request. In my example it will do it three times until it will pass error. Of course if first or second execution returns response then it won't be retried.
This behaviour is possible because HttpClient is returning cold observables
. It also leads to your problem and need to do any of this solutions.
This also allows to use cancelation token
mechanism but this is for later question to tell.