My service looks like this:
sortTraceGroups(): Observable<TraceGroup[]> {
const url = environment.servicesBaseUrl + 'api/trace/sort?sort=' + this.sortChosen;
return this.httpClient.post<TraceGroup[]>(url, this.traceGroups)
.pipe(catchError(this.handleError));
}
private handleError(error: HttpErrorResponse): Observable<never> {
if (error.error instanceof ErrorEvent) {
console.error('An error occurred:', error.error.message);
} else {
console.error(`Backend returned code ${error.status}, ` + `couldn't get response from server. ElasticSearch is probably down.`);
}
return throwError(`Error: couldn't get response from server.`);
}
}
This is a component which subscribe to http call
onSortChoose(sortChosen: SortChosen): void {
this.traceService.setSortChosen(sortChosen);
this.traceService.sortTraceGroups()
.subscribe(
traceGroupsSorted => {
this.traceGroups = traceGroupsSorted;
},
(error) => {
this.error = error;
}
);
}
Now I tried to show error message in my html like this
<div *ngIf="error" class="offset-md-3 col-md-6 alert alert-danger row justify-content-center" role="alert">
{{ error }}
</div>
It works fine when error occurs for the first time.
However when I do another call and it finish successfully I don't want to show the error message anymore. The only solution I come up is to update error message every time I do http call which seems to me incorrect.
onSortChoose(sortChosen: SortChosen): void {
this.traceService.setSortChosen(sortChosen);
this.traceService.sortTraceGroups()
.subscribe(
traceGroupsSorted => {
this.traceGroups = traceGroupsSorted;
this.error = ''; // do I need this line in every http call just to reset error message ?
},
(error) => {
this.error = error;
}
);
}
Is there an elegant way to display error in html only when http call fails and don't show when it ends successfully without changing error attribute every time ?
In this example it looks 'okayish' but sometime I need to share error between two components through service and it doesn't seems OK to call setter on service just to changed error message
Thanks