I'm making a request for a window of data based on a date and a range. The result of the request can be empty requiring me to make another request and change some parameters. The previous way I made the request was a recursive function that worked well but it can be a lot better.
Using a combination of rxjs pipe operators this can be one chain that works beautifully.
constructor(private http: HttpClient){}
someFunction() {
const retryObject = { foo: 1};
return of(retryObject)
.pipe(
switchMap(obj => {
return this.http(`http://some.name?foo=${obj.foo}`);
}),
map(result => {
if (result.error) {
// Update the foo value and it will try the request again with the new value
retryObject.foo++;
throw 'an error happened';
}
// Happy path
}),
retry([HOW MANY TIMES YOU WANT TO TRY THE REQUEST])
).subscribe(result => {
// Do something with your data
})
}
The magic here is the retry pipe in combination with throwing an error. The linked page used throwError but it didn't retry the request. You can't pass in a string or number into the of operator. Javascript is pass-by-value for those. You need a reference to an object that can be updated.