I filling some select options with observables by calling web services. The point is I am trying to get the http code errors in order to hide the form (if any of these the http code is different to 200) and show a message to the user.
Can someone suggest me a good practice to do this?
Thanks in advance!
Repo: https://github.com/jreategui07/testing-subscriptions-form
Mock server runs with: mockserver -p 8080 -m mock
GET.mock
HTTP/1.1 400 Bad Request
Access-Control-Allow-Origin: *
Content-Type: text/plain; charset=utf-8
Connection: keep-alive
[
{ "error": "c1", "error_des": "any error" }
]
You can add an error handler to all of your select observables. Notice in this I am only gathering the last error and hide the form so if there are multiple error you can use an array to the formHasError variable.
formHasError: string[] = [];
import { catchError } from 'rxjs/operators';
errorFn = catchError(e => {
const err = e && e.error && e.error[0] && e.error[0].error_des;
if(err){
this.formHasError.push(err);
}
return [];
});
this.colorSC$ = catalogueService.getColors().pipe(this.errorFn);
this.brandSC$ = catalogueService.getBrands().pipe(this.errorFn);
this.sizeSC$ = catalogueService.getSizes().pipe(this.errorFn);
this.fruitSC$ = catalogueService.getFruits().pipe(this.errorFn);
<form (ngSubmit)="onSubmit()" [formGroup]="anyForm" *ngIf="!formHasError.length">
...
</form>
<div class="error" *ngIf="formHasError.length">
Form has some errors:
<p *ngFor="let err of formHasError">{{err}}</p>
</div>