如何使用最后一个Rxjs版本实现http post timeout?
我用来设置超时我angular2 HTTP POST类似以下内容:如何使用最后一个Rxjs版本实现http post timeout?
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),这是不再有效。
超时需要一个Observable作为第一个参数,并且不接受“新错误”,我该怎么做/写这个?
THX您在您的帮助
注:当我删除了“新的错误(...)”,我的代码是那么有效,但在运行时,我该怎么面对以下错误
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
});
****** UPDATE折角> = 4.3和Rxjs> = 5.2.2 ******
随着RXJS 5.2的推出,timeout
运营商可以使用新推出的pipe
完成。此外,将它作为可导出的运算符导入可能会减小bundle的大小(以防所有使用的运算符都将被导入为可导出的)。
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
});
是的,你需要导入
import 'rxjs/add/operator/timeout';
据透露,你有其他的包,如果你需要他们
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/timeout';
...
当Rxjs> = 5.2时,超时值可以导入为可运算符,例如'rxjs/operators/timeout'中的import {timeout};'我用一个例子更新了我的答案 –
检查问题的导入回答,请 –
是的这是一个突破性的变化,当他们移动到5.0 https://github.com/ReactiveX/rxjs/commit/98 ea3d221e0b1c2da66e09b525a165abfa7fb460 – shusson
现在这个'Timeout exceeded'消息在哪里? – user630209