'Angular cancel observable and call service method again?
I have a service method that needs to call itself again if there are error conditions in the data returned.
Here's my simplified service call, omitting types, etc...
class LibraryService {
translate(translationRequest): Observable<ITranslation> {
this.httpClient
.post<string>(url, formData, { ... }
.pipe(
take(1),
map(response => {
if (response.errors) {
// modify translationRequest
const updatedTranslationRequest = {
...,
};
this.translate(updatedTranslationRequest);
}
return response;
}),
map(response => ...),
);
}
}
What I need to do is cancel the observable if there are errors in the response, modify the request and call translate again.
What's currently happening is the next map operation is called and the translate function is not called again, or if it is being called, it's getting swallowed as I never see an additional network request.
How can I make the translate method start over?
Solution 1:[1]
Here is a simple demonstration
const translatePostMethod = interval(1000); //Demonstration purpose only
const translateSubscription = translatePostMethod.pipe(
mergeMap((val) => {
if (val > 5) {
//If error happened
return throwError('Error!');
}
return of(val);
}),
//retry another time on error
retry(1)
);
const subscribe = translateSubscription.subscribe({
next: (val) => console.log('-----', val),
error: (val) => console.log(`${val}: Retried 1 times then quit!`),
});
Here is a stackblitz link to get your hands dirty
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dibyanshu Banerjee |
