首页 > 解决方案 > 忽略管道延迟的 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)
      }
)

只要请求完成,就会导致错误响应忽略它并在控制台上打印,从而忽略它。

标签: angulartypescriptrxjsdelayrxjs-pipeable-operators

解决方案


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)
)

推荐阅读