使用 Angular 更改请求超时

问题描述 投票:0回答:1

我目前正在使用 Angular 的 rxjs 和 httpclient 来发出 get 请求。它看起来像这样:

  get<T>(path: string): Observable<T> {
    return this.http
      .get<T>(path, { headers: this.httpOptions.headers })
      .pipe(timeout(5000), catchError(this.handleError));
  }

但是如果持续时间超过一秒,我的请求总是会被取消。

我尝试发送标头中的

timeout: 5000
,但没有成功。

然后我尝试在 Pipe() 内发送 timeout(5000) 方法,但这也不起作用。

我无法编辑API来缩短响应时间。

angular rxjs
1个回答
0
投票

您没有正确使用

timeout
运算符。您必须提供一个备份可观察值,以防原始可观察值在给定的超时时间内未能发出某些内容。

因此,您将拥有以下代码:

get<T>(path: string): Observable<T> {
    const request$ = this.http.get<T>(path, { headers: this.httpOptions.headers });

    return request$.pipe(
      timeout({
        each: 5000,
        with: () => throwError(() => new CustomTimeoutError()) //throw an error in case of timeout, or other observable
      }), 
      catchError(error => {
        console.error('Request timed out or encountered an error:', error); // Handle timeout or other errors
        return of(null); 
      })
    );
 }

您可以在超时时抛出自定义错误,或切换到不同的可观察对象(备份端点)。

希望这对您有帮助! :)

© www.soinside.com 2019 - 2024. All rights reserved.