gpt4 book ai didi

Angular2,RxJS 主题 http 请求 - 错误请求不会再次触发

转载 作者:行者123 更新时间:2023-12-03 07:52:33 24 4
gpt4 key购买 nike

收到 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 中取消订阅)

谢谢!

编辑 编辑 - 工作示例(由 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
}
});

最佳答案

您遇到的问题归结为"The Observable contract" .一个链只能发出一个错误通知,因此当您的 this.bookingService.update发出错误链被处理(取消订阅)。发射更多 next来自 saveBookingObservable 的通知因此没有效果。

根据您想要做什么,您似乎可以附加 retry()之后 switchMap()这将自动重新订阅。

关于Angular2,RxJS 主题 http 请求 - 错误请求不会再次触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59918761/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com