我正在尝试显示我的errorHandler生成的后端错误,但未显示任何内容。
我怎么显示它?
它返回undefined
HTML
//This triggers the observable, if it has an error it sets that error to the variable backendError
{{(pickupAvailabilityList$ | async)}}
{{ backendError}}
组件TS
getPickupAvailability(
equipmentLookup: EquipmentID[]
): Observable<PickupAvailability[]> {
this.backendError = this.pickupAvailabilityService.getErrorMessage();
return this.pickupAvailabilityService.getAmountDue(equipmentLookup);
}
SERVICE TS getErrors()
中的控制台日志给了我undefined
getAmountDue(equipmentID: EquipmentID[]): Observable<PickupAvailability[]> {
this.errorHandler.errorMessages = '';
return this.http
.post<PickupAvailability>(
this.BASE_URL + this.AMOUNT_DUE_URL,
equipmentID
)
.pipe(catchError(this.errorHandler.handleError));
}
getErrorMessage(): string {
this.errorMessage = this.errorHandler.errorMessages;
return this.errorHandler.errorMessages;
}
错误处理程序服务,将打印控制台日志
handleError(error: HttpErrorResponse) {
// To know the version of RxJS npm list --depth=0
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred: ', error.error.message);
this.errorMessages =
error.error.message;
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}` + ` body was: ${error.message}`
);
this.errorMessages =
`Backend returned code ${error.status}` + ` body was: ${error.message}`;
}
// return an observable with a user-facing error message
return _throw('Something bad happened; please try again later.');
}
答案 0 :(得分:1)
您需要执行以下操作:
.pipe(catchError((err,caught)=>{
return this.errorHandler.handleError();
}));
这样,您的handleError
方法就不会丢失其定义的服务的上下文。