I have this setup: A user inputs an employee code, then I make an http call to an API that returns some extended data. If the code is incorrect, the API responds with a "Not Found" Error. I had the problem that the Observable just ended the subscription if the user types an incorrect code (as expected according to the specification), so I am using the retryWhen operator to handle the error and resubscribe, expecting the user to input a correct code.
The problem is that the logic inside retryWhen is only being executed for the first time an error happen. If the user fails two times, or even if the user fails once, then inputs a right code and then another time inputs a bad one, the code inside retryWhen is not reached.
export class EmployeeService {
constructor(private http: HttpClient) { }
getEmployee(code: string): Observable<Employee> {
const baseUrl = config.employeesUrl
return this.http.get<Employee>(`${baseUrl}/${code}`)
}
}
import { Component, OnInit } from "@angular/core";
import { Cart } from "src/app/interfaces/cart.interface";
import { fromEvent, timer } from "rxjs";
import { debounce, switchMap, retryWhen } from "rxjs/operators";
import { EmployeeService } from "../../services/employee.service";
import { AlertController } from "@ionic/angular";
@Component({
selector: "app-set-employee",
templateUrl: "./set-employee.page.html",
styleUrls: ["./set-employee.page.scss"]
})
export class SetEmployeePage implements OnInit {
constructor(
private employeeService: EmployeeService,
private alert: AlertController
) {}
cart: Cart = {
employee: { code: null, name: null },
transactions: null
};
async presentAlert() {
const alert = await this.alert.create({
header: "Error",
subHeader: "",
message: "Some Alert",
buttons: ["OK"]
});
await alert.present();
}
ngOnInit() {
const input = document.getElementById("codigo");
const $input = fromEvent(<HTMLInputElement>input, "keyup");
$input
.pipe(
debounce(() => timer(1000)),
switchMap(event =>
this.employeeService.getEmployee(event.target["value"])
),
retryWhen(error => {
console.log("retrying...");
this.cart.employee.name = null;
this.presentAlert();
return error;
})
)
.subscribe(
data => {
this.cart.employee = data;
},
error => console.log(error)
);
}
}