处理异步管道时出错 - Angular
Error handling async pipe - Angular
我们正在尝试了解如何使用异步管道进行错误处理。如果我们订阅了 http GET
请求,我们知道该怎么做,但我们没有订阅它。我必须使用 .pipe
吗?
TS
getAmountDue(equipment: Equipment[]): Observable<PickupAvailability> {
return this.http.post<PickupAvailability>(
this.BASE_URL + this.AMOUNT_DUE_URL,
equipment
);
HTML
{{ testAmountDue$ | async }}
我决定回答我自己的问题,因为我找到了解决方案,为了解决我的问题,我决定使用基于此 [= 的 .pipe 解决方案44=] 请求是一个非常简单的请求。
首先我们编写如下错误处理程序:
TS-取货-availability.service.ts
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', 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.error}`);
}
// return an observable with a user-facing error message
return throwError(
'Something bad happened; please try again later.');
};
请注意,此处理程序 return 是一个带有用户友好错误消息的 RxJS ErrorObservable。服务的消费者期望服务方法 return 某种 Observable,甚至 "bad" 一个。
现在,您将 Observables return 由 HttpClient 方法编辑,并将它们通过管道传递给错误处理程序。
TS-取货-availability.service.ts
getAmountDue(equipment: Equipment[]): Observable<PickupAvailability> {
return this.http.post<PickupAvailability>(
this.BASE_URL + this.AMOUNT_DUE_URL,
equipment
).pipe(
catchError(this.handleError)
);
}
我们正在尝试了解如何使用异步管道进行错误处理。如果我们订阅了 http GET
请求,我们知道该怎么做,但我们没有订阅它。我必须使用 .pipe
吗?
TS
getAmountDue(equipment: Equipment[]): Observable<PickupAvailability> {
return this.http.post<PickupAvailability>(
this.BASE_URL + this.AMOUNT_DUE_URL,
equipment
);
HTML
{{ testAmountDue$ | async }}
我决定回答我自己的问题,因为我找到了解决方案,为了解决我的问题,我决定使用基于此 [= 的 .pipe 解决方案44=] 请求是一个非常简单的请求。
首先我们编写如下错误处理程序:
TS-取货-availability.service.ts
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', 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.error}`);
}
// return an observable with a user-facing error message
return throwError(
'Something bad happened; please try again later.');
};
请注意,此处理程序 return 是一个带有用户友好错误消息的 RxJS ErrorObservable。服务的消费者期望服务方法 return 某种 Observable,甚至 "bad" 一个。
现在,您将 Observables return 由 HttpClient 方法编辑,并将它们通过管道传递给错误处理程序。
TS-取货-availability.service.ts
getAmountDue(equipment: Equipment[]): Observable<PickupAvailability> {
return this.http.post<PickupAvailability>(
this.BASE_URL + this.AMOUNT_DUE_URL,
equipment
).pipe(
catchError(this.handleError)
);
}