Angular 处理异步管道时出错-角度
我们试图了解如何使用异步管道进行错误处理。如果我们订阅了httpAngular 处理异步管道时出错-角度,angular,angular-httpclient,Angular,Angular Httpclient,我们试图了解如何使用异步管道进行错误处理。如果我们订阅了httpGET请求,我们知道怎么做,但我们没有订阅它。我必须使用.pipe TS getAmountDue(equipment: Equipment[]): Observable<PickupAvailability> { return this.http.post<PickupAvailability>( this.BASE_URL + this.AMOUNT_DUE_URL, eq
GET
请求,我们知道怎么做,但我们没有订阅它。我必须使用.pipe
TS
getAmountDue(equipment: Equipment[]): Observable<PickupAvailability> {
return this.http.post<PickupAvailability>(
this.BASE_URL + this.AMOUNT_DUE_URL,
equipment
);
我决定回答我自己的问题,因为我找到了解决方案,为了解决我的问题,我决定使用.pipe解决方案,因为这个POST请求非常简单 首先,我们编写一个错误处理程序,如下所示: TS-pick-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.');
};
getAmountDue(equipment: Equipment[]): Observable<PickupAvailability> {
return this.http.post<PickupAvailability>(
this.BASE_URL + this.AMOUNT_DUE_URL,
equipment
).pipe(
catchError(this.handleError)
);
}
请注意,此处理程序返回一个带有用户友好错误消息的RxJS ErrorObservable。服务的使用者期望服务方法返回某种可观察的,甚至是“坏”的
现在,您获取由HttpClient方法返回的可观察对象,并通过管道将它们传递到错误处理程序
TS-pick-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.');
};
getAmountDue(equipment: Equipment[]): Observable<PickupAvailability> {
return this.http.post<PickupAvailability>(
this.BASE_URL + this.AMOUNT_DUE_URL,
equipment
).pipe(
catchError(this.handleError)
);
}
getAmountDue(设备:设备[]):可观察{
返回this.http.post(
this.BASE\u URL+this.AMOUNT\u DUE\u URL,
设备
).烟斗(
catchError(this.handleError)
);
}
来源:您签出文档了吗?你有什么特别想要的吗?管道是一条路,拦截器是另一条路。。。只是不知道你想做什么。@andydangergenge天哪,有这么多人。我想对于这个简单的POST请求,我将不再使用管道。谢谢你!