http post请求中的Angular2超时

Rap*_*aph 17 post http angular

是否可以在发布请求中超时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')
        );
Run Code Online (Sandbox Code Playgroud)

Thi*_*ier 35

您可以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')
         );
Run Code Online (Sandbox Code Playgroud)


rea*_*pie 19

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

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))
Run Code Online (Sandbox Code Playgroud)

请查看文档,文档深入解释了可管道操作员.


Pet*_*ter 12

我修改了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')
     );
Run Code Online (Sandbox Code Playgroud)

  • 确认无法将错误作为Angular 4中的第二个参数传递 (3认同)