我的
服务
看起来像这样:
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.`);
}
}
这是一个
订阅http调用的
onSortChoose(sortChosen: SortChosen): void {
this.traceService.setSortChosen(sortChosen);
this.traceService.sortTraceGroups()
.subscribe(
traceGroupsSorted => {
this.traceGroups = traceGroupsSorted;
},
(error) => {
this.error = error;
}
);
}
现在我试图在我的
HTML格式
这样地
<div *ngIf="error" class="offset-md-3 col-md-6 alert alert-danger row justify-content-center" role="alert">
{{ error }}
</div>
当第一次出现错误时,它可以正常工作。
但是,当我再打一个电话并且它成功结束时,我不想再显示错误消息。我提出的唯一解决方案是每次进行http调用时更新错误消息,这在我看来是不正确的。
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;
}
);
}
有没有一种优雅的方法可以只在http调用失败时在html中显示错误,而在每次不更改错误属性的情况下不显示何时成功结束?
在这个例子中,它看起来是“好的”,但是有时我需要通过服务在两个组件之间共享错误,并且仅仅调用服务上的setter来更改错误消息似乎是不合适的。
谢谢