angular - 忽略管道延迟的 Http 发布请求
问题描述
在我的服务类中,我正在发出这样的帖子请求
// my-service.service.ts
sendRequest(
param: string
): Observable<HttpResponse<string>> {
return this.http.post<HttpResponse<string>>("", {
param
}).pipe(
retry(3),
)
}
因此,组件订阅了返回Observable
的
// my-component.ts
this.myService.sendRequest(
""
).subscribe(
res => {
console.log(res)
},
(err: HttpErrorResponse) => {
console.log(err.message)
}
)
正如您所注意到的,我正在执行将""
其转换为http://localhost:4200
不存在的发布请求,因此每个发布请求都会导致Cannot POST /
响应(404)。
我不明白为什么通过添加延迟
this.myService.sendRequest(
""
).pipe(delay(10000)).subscribe(
res => {
console.log(res)
},
(err: HttpErrorResponse) => {
console.log(err.message)
}
)
只要请求完成,就会导致错误响应忽略它并在控制台上打印,从而忽略它。
解决方案
delay
只会延迟排放,而不是错误。
我前段时间在 rxjs 的 repo 中打开了一个讨论 -> https://github.com/ReactiveX/rxjs/discussions/6519
我认为实现你想要的唯一方法是:
this.myService.sendRequest(
""
).pipe(
delay(10000),
catchError(err => timer(10000).pipe(
switchMap(() => throwError(() => err))
))
)
如果您认为这很难看,您可以随时将其封装在自定义运算符中:
const delayEverything = <T>(ms: number) => (source: Observable<T>) =>
source.pipe(
delay(ms),
catchError(err => timer(ms).pipe(switchMap(() => throwError(() => err))))
)
// ... and then use it as a regular operator
this.myService.sendRequest('').pipe(
delayEverything(10000)
)
推荐阅读
- php - getenv() 不会显示所有变量,即使它们已设置
- javascript - 搜索json对象并获取数据
- javascript - 如何同时动态显示和隐藏 div?
- javascript - 如何防止 Three.js OBJLoader 将我的 obj 的所有部分合并到 1 个网格中?
- sql - 如何将 exec 结果分配给多个 sql 变量?
- javascript - 如何包含外部 HTML 头?
- java - Java:如何验证自然语言文本
- multithreading - 创建两个可变引用,它们对 Rust 中的结构是线程安全的
- gradle - 无法使用 Gradle 构建 Git 项目
- python - 如何使用 Requests POST 方法从网站获取搜索结果?