如何为angular2 + http请求实现超时 [英] How can I implement timeout for angular2+ http request

查看:163
本文介绍了如何为angular2 + http请求实现超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里只是常规请求,如下所示:

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?

推荐答案

您可以利用timeout观测值运算符,如下所述:

You can leverage the timeout operator of observables, as described below:

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);

有关更多详细信息,请参见本文(带有重试支持"部分):

See this article for more details (with the section "Retry support"):

这篇关于如何为angular2 + http请求实现超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆