I'm new to Angular/Typescript and using catchError RxJs. I'm also using .subscribe and pipe operators. I would like to use observable as much as possible, combining it with RxJS operators. On submission of my form, frontend calls the API and a new product gets created and would like to have proper error handling for Error Codes of 400 and 500 using HttpErrorResponse. I wrote below code but not sure if I'm doing the error handling correctly as I get the below error (see bottom).
app.component.ts
onSubmit(): void {
if (this.form.valid) {
console.log('Creating product:', this.form.value);
this.http.post('/api/create', {
productName: this.form.value.productName,
}).pipe(catchError(err => {
if(err instanceof HttpErrorResponse && err.status == 500 || err.status == 502 || err.status == 503) {
this.err = "Server Side Error";
return throwError(err);;
}
else if(err instanceof HttpErrorResponse && err.status == 400){
this.err = "Bad Request";
return throwError(err);;
} else if(err instanceof HttpErrorResponse && err.status == 422){
this.err = "Unprocessable Entity - Invalid Parameters";
return throwError(err);;
}
})
.subscribe(
resp => this.onSubmitSuccess(resp), err => this.onSubmitFailure(err)
);
}
this.formSubmitAttempt = true;
}
private onSubmitSuccess(resp) {
console.log('HTTP response', resp);
this.productID = resp.projectID;
this.submitSuccess = true;
this.submitFailed = false;
}
private onSubmitFailure(err) {
console.log('HTTP Error', err);
this.submitFailed = true;
this.submitSuccess = false;
}
Errors:
app.component.ts - error TS2339: Property 'err' does not exist on type 'AppComponent'.
app.component.ts:124:16 - error TS2339: Property 'subscribe' does not exist on type 'OperatorFunction'.}).subscribe(