For creating a new product using a backend API, the Angular frontend code needs to make a call to the API. I am interested in learning how to implement error handling with the use of .subscribe method. Currently, I am utilizing HTTPClient along with Observable and exploring the error handling capabilities provided by RXJS.
The application is expected to interact with the API as an Observable and subscribe to it.
The API at /create endpoint should handle both success and failure scenarios: - If the API returns 200, a success message should be displayed. - If the API returns 400, it should trigger an error.
Pseudo Code:
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
ID = 'foo';
this.http.post('/api/create', {
productName: this.form.value.productName,
productValue: this.form.value.productValue,
}).subscribe(
resp => this.onSubmitSuccess(resp), err => this.onSubmitFailure(err)
);
private onSubmitSuccess(resp) {
console.log(resp);
this.ID = resp.ID;
this.submitSuccess = true;
this.submitFailed = false;
}
private onSubmitFailure(resp) {
console.log(resp);
this.submitFailed = true;
this.submitSuccess = false;
}