Angular中的延迟HTTP请求

时间:2018-07-18 13:33:16

标签: angular rxjs rxjs6

我很好奇。我只是尝试用.pipe( delay( 5000 ) )...来延迟Angular(6.x)中的HTTP请求,但是看起来,RxJS只是延迟了最终响应而不是服务器调用。但是我真的需要延迟真正的服务器调用。通过HttpInterceptor在AngularJS中这不是问题,但我无法使其正常工作。有什么想法吗?

提前谢谢。

更新:

我已经尝试过HttpInterceptor了,但这也不起作用。我有一个CustomHttpClient,它将正在运行的请求url放入数组中,并在完成后将其删除。某些请求不能并行运行,因此我必须检查列表中是否有来自例如/ api / somePath。如果此类url在列表中,则当前请求必须延迟。在AngularJS的HttpInterceptor中可以正常工作。

5 个答案:

答案 0 :(得分:2)

我喜欢那些拦截器,因为您可以用它们做很多魔术。

在拦截器中处理http呼叫的响应

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      tap(response=> console.log(response) )  // <== or do some other magic
    );
  }
}

在拦截器中处理http调用的请求,例如延迟它。

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return timer(2000).pipe(         // <== Wait 2 Seconds
      switchMap( ()=> next.handle(request) )   // <== Switch to the Http Stream
    )
  }
}

在两种情况下,它都是相同的“ intercept(...)”方法,但是对“ next.handle()”的处理不同。

热烈的问候

答案 1 :(得分:1)

再次,您可以使用HttpInterceptor中的@angular/common/http来为您执行此操作。

或者只是:

Observable.timer(5000).pipe(tap( // do your stuff ))

答案 2 :(得分:1)

从其他可观察对象(在这种情况下为计时器可观察对象)开始,然后切换到您的http客户端可观察对象:

timer(1000).pipe(
 switchMap(() => this.http.get('')),
)
.subscribe();

of(null).pipe(
 delay(1000),
 switchMap(() => this.http.get('')),
)
.subscribe();

答案 3 :(得分:1)

如果要使用RxJS延迟通话本身,可以使用timer

timer(5000)
  .pipe(
    concatMap(() => of(42)),
  )
  .subscribe(...)

答案 4 :(得分:0)

您可以使用RxJS Observable.timer

let myRequest = this.http.get(...);
let pollingSubscription = myRequest
 .expand(() => Observable.timer(5000).flatMap(() => myRequest))
 .subscribe();