简体   繁体   English

如何为 angular2+ http 请求实现超时

[英]How can I implement timeout for angular2+ http request

Here is just regular request looking like that:这是看起来像这样的常规请求:

this.people = http.get('http://localhost:3000/users')
                  .map(response => response.json());

Is there any way to delay/timeout that?有什么办法可以延迟/超时吗?

You can leverage the timeout operator of observables, as described below:您可以利用 observable 的timeout运算符,如下所述:

return this.http.get('http://api.geonames.org/postalCodeSearchJSON',
          { search: params })
    .retryWhen(error => error.delay(500))
    .timeout(2000, new Error('delay exceeded')) // <------
    .map(res => res.json().postalCodes);

The return value of http.get() is an observable, not the response. http.get()的返回值是可观察的,而不是响应。 You can use it like:你可以像这样使用它:

getPeople() {
  return http.get('http://localhost:3000/users')
      .timeout(2000)
      .map(response => response.json());
  }
}

foo() {
  this.subscription = getPeople.subscribe(data => this.people = data)
}

// to cancel manually
cancel() {
  this.subscription.unsubscribe();
}

See also https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/timeout.md另见https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/timeout.md

If you are using RxJS version 6 and above the current syntax is this:如果您使用的是 RxJS 6 及以上版本,当前的语法是这样的:

import { timeout } from 'rxjs/operators';从'rxjs/operators'导入{超时};

getPeople(){
  return this.http.get(API_URL)
  .pipe(
      timeout(5000) //5 seconds
  );

As with the new version, you must pipe to use the timeout .与新版本一样,您必须通过pipe来使用timeout And to get the response you can use map inside.要获得响应,您可以在里面使用map The complete code is as below.完整的代码如下。

import { map, timeout, catchError } from 'rxjs/operators';

const sub: any = this.httpClient.post(this.baseUrl, body)
    .pipe(timeout(Config.SesamTimeout),
        catchError((err: any) => {
            this.handleTimeout(err);
            return of(null);
        }),
        map((v: SesamResponse) => {
            if (v) {
                const a: SearchResultGroup[] = this.convertSesamResponseToApiFileItem(v);
                return a;
            }
        }));

Here Config.SesamTimeout is the time in milliseconds.这里的Config.SesamTimeout是以毫秒为单位的时间。

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

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