I am making an HTTP request to the server to get a file upload status which takes a little time around 3 to 4 minutes. If the request is in the pending state or it has not returned the status of success or error
then I want to recall the HTTP request until I get the response.
I am using a set timeout recursively, Is there any way to achieve it using RXJS operators
getImportStatus(): void {
this.restaurantService
.getImportStatus()
.pipe(takeUntil(this.destroy$))
.subscribe(
(res) => {
if (
res.result.status == 'error' ||
res.result.status == 'success'
) {
this.spinner.hide();
if (res.result.status == 'error') {
this.toastr.error(
res.result.restaurant.message,
'Error!'
);
} else {
this.toastr.success(
res.result.message,
'Success'
);
}
} else {
//retry the same http request
//after every three seconds
setTimeout(() => {
this.getImportStatus();
}, 3000);
}
},
(err) => {
console.log(err);
}
);
}
CodePudding user response:
you can use the interval
operator from RXJS to perform the same task. The interval operator emits a sequence of numbers at a given time interval, and you can use it to send a request to the server at a fixed time interval until the desired response is received.
import { interval, Subscription } from 'rxjs';
private subscription: Subscription;
getImportStatus(): void {
this.subscription = interval(3000)
.pipe(
takeUntil(this.destroy$),
switchMap(() => this.restaurantService.getImportStatus())
)
.subscribe(
(res) => {
if (res.result.status == 'error' || res.result.status == 'success') {
this.spinner.hide();
if (res.result.status == 'error') {
this.toastr.error(
res.result.restaurant.message,
'Error!'
);
} else {
this.toastr.success(res.result.message, 'Success');
}
this.subscription.unsubscribe();
}
},
(err) => {
console.log(err);
}
);
}