如何使用最新的 Rxjs 版本实现 http post 超时?

How to implement http post timeout with last Rxjs version?

我曾经为我的 angular2 http post 设置超时,如下所示:

this.http.post('myurl',
      body, {headers: headers})
      .timeout(2000, new Error('Timeout exceeded'))
      .map(res => res.json())
      .subscribe((stuff) => {
         //Do stuff
      }, (errorResponse: any) => {
        //Manage error
      });

但是对于最新版本的 Rjxs (5.0.1),这不再有效。

Timeout 需要一个 Observable 作为第一个参数并且不接受 "new Error",我应该如何 do/write 那个?

提前感谢您的帮助

注意:当我删除 "new Error(...)" 时,我的代码是有效的,但在运行时,我将面临以下错误

Error: Uncaught (in promise): TypeError: _this.http.post(...).timeout is not a function TypeError: _this.http.post(...).timeout is not a function

知道了,我必须包括以下内容:

import 'rxjs/add/operator/timeout';

this.http.post('myurl',
  body, {headers: headers})
  .timeout(2000)
  .map(res => res.json())
  .subscribe((stuff) => {
     //Do stuff
  }, (errorResponse: any) => {
    //Manage error
  });

****** Angular >= 4.3 和 Rxjs >= 5.2.2 的更新 ******

随着 RXJS 5.2 的引入,timeout 运算符可以使用新引入的 pipe 来完成。此外,将其作为可出租运算符导入可能会减小包大小(以防所有使用的运算符都作为可出租运算符导入)。

Angular 4.3 介绍 HttpClientModule,它会在某个时候取代 HttpModule.

因此此处更新代码:

import {timeout} from 'rxjs/operators/timeout'; 

let headers: HttpHeaders = new HttpHeaders();
headers.append('Content-Type', 'application/json');

let body = {something: 'my_value'};

this.http.post('myurl',
  body, {headers: headers})
  .pipe( 
     timeout(2000)
  )
  .subscribe((stuff: any) => {
     //Do stuff
  }, (errorResponse: HttpErrorResponse) => {
    //Manage error
  });

****** Rxjs 的更新 >= 6 ******

上面的代码在 Rxjs v6 中仍然可以正常工作,但是 importtimeout 管道应该修改如下:

import {timeout} from 'rxjs/operators';

// same as above

是你需要导入

import 'rxjs/add/operator/timeout';

顺便说一句,如果你需要的话,你还有其他的包要导入

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/timeout';
...