【发布时间】:2020-05-12 02:21:29
【问题描述】:
收到 http 错误响应时遇到问题(来自后端的 422 验证错误)。
一旦收到 http 错误响应,我就无法再次触发请求(单击按钮时)。
1) 我有一个主题属性,我调用 .next(whatEverDataForTheRequest),以便将请求发送到 API。
2)在构造函数中,我订阅了主题(.asObservable),只要响应成功,一切都会正常,但发生错误时不会。
代码目前是这样的:
// Properties -> Subject + Observable, used when button is clicked
private saveBookingSubject: Subject<BookingUpdateInterface> = new Subject<BookingUpdateInterface>();
private saveBookingObservable = this.saveBookingSubject.asObservable();
单击按钮时,我创建一个有效负载/对象并像这样传入:
this.saveBookingSubject.next(payload)
然后在构造函数中,我有以下代码,当调用 .next 时会触发该代码。
const sub = this.saveBookingObservable.pipe(
tap(data => {
this.bookingError = null;
this.dialogCanClose = false;
}),
debounceTime(500),
switchMap(booking => {
return this.bookingService.update(booking).pipe(catchError(error => throwError(error)));
})
).subscribe((response: any) => {
// This works - Called on success
console.log('ok', response);
}, (http: HttpErrorResponse) => {
// This works - Gets called on error
console.log(http);
});
成功的请求按预期工作 - 但是当从后端收到错误时,调用:
this.saveBookingSubject.next(payload)
...在按钮被点击时被完全忽略 -> 订阅逻辑永远不会启动。
我在这里缺少什么? (我确实在 ngOnDestroy 中取消订阅)
谢谢!
EDIT EDIT - 工作示例(由 Martin 发布)
const sub = this.saveBookingObservable.pipe(
debounceTime(500),
switchMap(booking => {
return this.bookingService.update(booking).pipe(
catchError(httpError => {
this.bookingError = httpError.error.data;
return of(null);
})
);
}),
retry(1)
).subscribe((response: any) => {
// Handle success
}
});
【问题讨论】:
-
它看起来不是完整的代码,我无法重现问题,所以我想也许你需要retry operator
标签: angular error-handling rxjs observable subject-observer