我正在努力找出如何使用Angular http和promises检测请求超时。我正在使用以下代码来格式化来自我的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)
  );
}


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

关于javascript - Angular http.get()检测调用超时,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55679319/

10-09 18:07
查看更多