Imagine having a situation where a component has a method that triggers an http request defined in a service. The observable is subscribed to within the component:
Component:
fetchData() {
this.apiService.fetchDataFromServer().subscribe(
response => console.log(response),
error => console.error(error)
);
}
API Service:
fetchDataFromServer() {
return this.http.get();
}
In case of a request failure, it is desired to display an error modal with two buttons: "reload" and "cancel". Clicking on either button should close the modal.
One way to handle this issue inexpensively would be to simply re-trigger fetchData()
from the error scenario in the component. However, handling errors at the service level would result in a cleaner solution.
I am currently investigating how to manage the button click event. By using pipe
and catchError
, it seemed impractical to patiently wait for the reload button click within the service method. Utilizing retryWhen
seems like a potential solution, but I am struggling with the implementation.
Below is my attempt to enhance the API Service:
// The modal with the two buttons will trigger
// - this.apiService.button$.next(true) if the user chooses to reload, or
// - this.apiService.button$.next(false) if the user opts not to reload
button$ = new Subject<boolean>();
fetchDataFromServer() {
return this.http.get().pipe(
retryWhen((errors: Observable<any>) => {
this.openErrorModal(); // a method to display the error modal
// How can I incorporate the button$ subject here?
// I attempted
// - return this.button$.pipe(), and
// - return errors.pipe(),
// but struggled to finalize the implementation
}
);
}
openErrorModal() {
// Display a modal with a simple interface
}
The ultimate aim is for the component to receive the data or error regardless of the number of times the request was made. Essentially, the error modal should appear whenever the request fails, allowing the user to potentially enter into an infinite loop by choosing to reload continuously. Once the user clicks "cancel," further requests should cease.
Note: This problem has been streamlined significantly to focus solely on the core issue.