【问题标题】:Angular Set HTTP Timeout [duplicate]角度设置 HTTP 超时 [重复]
【发布时间】:2019-12-13 21:48:20
【问题描述】:

我正在寻找一种方法来停止/终止超过特定时间的 http 请求。 那么在 Angular 5 中,是否可以为 http 请求设置超时?

如果有办法,我们怎样才能在超时后做一些事情,比如执行某个函数?

本题列出的方法

How can I implement timeout for angular2+ http request 给出错误:

错误 TS2339:“可观察”类型上不存在属性“超时”。

【问题讨论】:

  • @bugs 阅读可能重复的错误描述

标签: angular http


【解决方案1】:

正如评论中提到的,您需要使用timeout 运算符。但是,链接的答案有点过时了。从 rxjs 5.5.2 开始,您需要将 pipe 方法与 lettable 运算符一起使用。假设您使用HttpClient 提出请求,则不需要map(response => response.json())

像这样:

import { timeout, catchError } from 'rxjs/operators';
import { of } from 'rxjs/observable/of';

http.get('https://example.com')
   .pipe(
      timeout(2000),
      catchError(e => {
        // do something on a timeout
        return of(null);
      })
    )

【讨论】:

  • 那么我从哪里得到响应?
  • http.get('https://example.com').pipe(...).subscribe(response => console.log(response))
  • 我收到一个错误:Argument of type '(e: any) => void' is not assignable to parameter of type '(err: any, caught: Observable<Object>) => ObservableInput<{}>'. Type 'void' is not assignable to type 'ObservableInput<{}>'.
  • 你需要从catchError返回一个observable。查看我的编辑。也请投票和/或接受我的回答:)
  • 返回 null 好吗?
猜你喜欢
  • 2018-08-28
  • 2014-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-27
  • 1970-01-01
  • 1970-01-01
  • 2020-06-12
相关资源
最近更新 更多