【问题标题】:Send "Error time out" after specific amount of time in angular在角度的特定时间后发送“错误超时”
【发布时间】:2023-01-14 00:30:49
【问题描述】:

我正在进行 API 调用,但有时需要更多时间才能获得响应。我想设置一个特定的时间量,比方说“8secs”,如果前面提到的时间已经过去,则等待响应 API 调用应该停止并在控制台中显示“ERROR time out”。

我试过在管道中添加超时,因为其他帖子是这样说的:

`this.http.post<RefreshTokenResponseMessage>(url, tokenRequestMessage, { headers }).pipe(timeout(20)).toPromise()`

但它显示超时错误。

我也尝试在标头中添加超时参数,如下所示:

`const headers = new HttpHeaders({authorization: 'Bearer ${sessionstorage.getItem('authData')}',timeout: '${2}',});
return this.httpClient.get(URL, { headers });`

但我也面临同样的问题,即它没有触发错误。

有没有人遇到过这样的事情?

【问题讨论】:

    标签: javascript angular api http fetch


    【解决方案1】:

    如果你想在 8 秒后 http-response 还没有到达的情况下打印一个 console.error,你可以这样实现:

    this.http.post<RefreshTokenResponseMessage>(url, tokenRequestMessage, { headers }).pipe(
        tap((res) => console.log('Result: ', res)),
        timeout(8000),
        catchError(_ => {
            console.error('ERROR time out');
            return EMPTY;
        })
    )       
    .subscribe();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-25
      • 1970-01-01
      • 1970-01-01
      • 2015-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多