繁体   English   中英

Angular http.get() 检测调用超时

[英]Angular http.get() detecting call timeout

我正在努力弄清楚如何使用 Angular http 和 promise 检测请求超时。 我正在使用以下代码来格式化来自我的 API 的响应,它目前正在超时,我想用错误消息处理它,当我的 API 返回实际错误消息时,这里的代码确实有效,只是它甚至没有被命中当 API 超时时。

我找不到任何关于 Angular http 有处理超时的方法的文档,所以任何事情都会有帮助,谢谢!

代码:

/**
  * GET from the API
  * @param params  What to send
  * @param path    Where to go
  */
public get(path, params): Promise<any> {
  return this.formatResponse(
    this.http.get(this.apiUrl + path, params)
  );
}

/**
  * Takes the API response and converts it to something usable
  * @param response Promise of formatted data
  */
public formatResponse(response): Promise<any> {
  return response
    .toPromise()
    .then(r => r.json().data)
    .catch(e => {
      console.log('hitting error');
      const errors = e.json().errors;
      let error = 'Something went wrong, please try again in a few minutes.';

      if (errors && errors.length > 0) {
        error = errors[0].message;
      }

      // Create alert
      this.utilities.createAlert(
        'Whoops!',
        error
      );

      // Throw the error
      throw new Error(error);
    });
}

在网络选项卡中进行监控时,我看到:

加载资源失败:请求超时。

那这个呢

public get(path, params): Promise<any> {
  return this.formatResponse(
    this.http.get(this.apiUrl + path, params).pipe(timeout(10000), catchError(this.handleError)
  );
}

并根据需要创建错误处理程序。 其余的将保持不变。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM