如何捕获超时请求

时间:2018-07-10 14:06:27

标签: javascript angular ionic2 ionic3

这是我的代码:

properties.service.ts

get(stringParams) {
    let headers = new Headers({
      "X-AUTH-APIKEY":  API_KEY
    });

    this.options = new RequestOptions({
      headers: headers
    });
    return this.http
      .get(`${API_URL}/properties/?${stringParams}`, this.options)
      .timeout(50)
      .map((response: Response) => response.json())
  }



posts.ts

    this.propertiesService.get(arrayParams).subscribe((data: any) => {

    }), (err) => { console.log("timeoout")};

我将50设置为超时,因此被解雇了,但我无法以这种方式捕获错误

}), (err) => { console.log("timeoout")};

我收到此错误:

TimeoutError {name: "TimeoutError", stack: "TimeoutError: Timeout has occurred↵    at new Time…http://localhost:8100/build/polyfills.js:3:10143)", message: "Timeout has occurred"

编辑:

this.propertiesService.get(arrayParams).subscribe((data: any) => {

        }), (err) => { console.log("timeoout")};

get(stringParams) {

    return this.http
      .get(`${API_URL}/properties/?${stringParams}`, this.options)
      .timeout(50)
      .map((response: Response) => response.json())
      .catch(this.handleError);
}

private handleError(error: any) { 
  return Observable.throw(error);
}

我尝试了此解决方案,但仍然出现此错误enter image description here

解决方案:

代码应如下所示(subscribe中的err):

}, (err) => { console.log("timeoout")});

1 个答案:

答案 0 :(得分:5)

err应该放在subscribe

之内
this.propertiesService.get(arrayParams).subscribe((data: any) => {

    }, (err) => { console.log("timeoout")});

您应该catch例外:

get(stringParams) {

    return this.http
      .get(`${API_URL}/properties/?${stringParams}`, this.options)
      .timeout(50)
      .map((response: Response) => response.json())
      .catch(this.handleError);
}

private handleError(error: any) { 
  return Observable.throw(error);
}