如何在 Angular 中向用户显示 httpClient 错误



我的服务如下所示:

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;
}
);
}

有没有一种优雅的方法可以在 html 中显示错误,仅在 http 调用失败时显示错误,并且在成功结束时不显示,而无需每次都更改错误属性?
在这个例子中,它看起来"不错",但有时我需要通过服务在两个组件之间共享错误,并且仅仅为了更改错误消息而在服务上调用setter似乎不行

谢谢

没有一种优雅的方法仅在调用时在 html 中显示错误http失败,并且在不更改错误的情况下成功结束时不显示 每次都有属性?

不,您必须取消设置该属性。

但是,您可以使用complete处理程序来清除属性,而不是next处理程序。 有三个函数可用于将数据发送到可观察量的订阅者:

  1. next:将任何值(如数字、数组或对象(发送到其 用户。
  2. error:发送 JavaScript 错误或异常
  3. complete:不发送任何值
onSortChoose(sortChosen: SortChosen): void {
this.traceService.setSortChosen(sortChosen);
this.traceService.sortTraceGroups()
.subscribe(
traceGroupsSorted => {
this.traceGroups = traceGroupsSorted;
},
(error) => {
this.error = error;
},
() => this.error = ''; // do I need this line in every http call just to reset error message ?
);
}

Defining observers

最新更新