http post请求中的Angular2超时

http post请求中的Angular2超时,http,post,angular,Http,Post,Angular,是否可以在post请求中超时3秒?怎么做 我现在的代码 this.http.post('myUrl', MyData, {headers: Myheaders}) .map(res => res.json()) .subscribe( data => this.ret = data, error => console.debug('ERROR', error), (

是否可以在post请求中超时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')
         );

您可能需要像这样导入超时

导入'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问题的讨论,timeout函数现在总是抛出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')
     );

谢谢回复,但它对我不起作用,它总是执行“返回新错误('超过延迟')”哦,对不起!我的回答有一个打字错误。我更新了它。如果您可以重新尝试…@ThierryTemplier而不是返回
新错误
,我们应该抛出一个错误
抛出新错误
,这样您就可以在控制台中以实际的
红色
@PankajParkar Nope看到该错误,而不是用console.debug读取它。我们应该抛出它。无论如何,它将错误作为参数传递给函数。如果抛出,这是一个语法错误,并且总是抛出,而不仅仅是在超时时。上面是什么类型的超时?连接超时?套接字超时?看起来这只是一个可观察到的超时。我感到困惑的是,如果服务器正确地处理了响应并在2000毫秒以上返回给客户端,那么会发生什么?确认错误不能作为第二个参数传递,http请求在发送请求4分钟后给出ERR_EMPTY_响应。这次有没有办法增加?。我尝试了.timeout()方法。但在4分钟后仍然会出现错误。对于答案,需要导入角度5+