[英]Angular2 timeout in http post request
是否可以在發布請求中設置 3 秒的超時時間? 如何 ?
我的代碼
this.http.post('myUrl',
MyData, {headers: Myheaders})
.map(res => res.json())
.subscribe(
data => this.ret = data,
error => console.debug('ERROR', error),
() => console.log('END')
);
您可以像這樣使用timeout
運算符:
this.http.post('myUrl',
MyData, {headers: Myheaders})
.timeout(3000, new Error('timeout exceeded'))
.map(res => res.json())
.subscribe(
data => this.ret = data,
error => console.debug('ERROR', error),
() => console.log('END')
);
您可能需要像這樣導入超時
import 'rxjs/add/operator/timeout'
如果沒有 rxjs 5.0.1
和 angular 2.3.1
,我就無法讓它工作
2018 年 4 月 20 日編輯
請不要以這種方式導入操作符,在 rxjs +5.5 中,您可以導入這樣的操作符
import { timeout } from 'rxjs/operators/timeout';
// Use it like so
stream$.pipe(timeout(3000))
請查看此文檔,其中詳細解釋了可管道操作符。
我修改了 Thierry 的答案以使其與最新版本一起使用。 需要去掉超時函數的第二個參數。 根據關於 angular-cli 問題的討論,超時函數現在總是拋出 TimeoutError 。
this.http.post('myUrl',
MyData, {headers: Myheaders})
.timeout(3000)
.map(res => res.json())
.subscribe(
data => this.ret = data,
error => console.debug('ERROR', error),
() => console.log('END')
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.