Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delayed HTTP Request in Angular

I'm curious. I just tried to delay a HTTP Request in Angular (6.x) with .pipe( delay( 5000 ) )... but it looks like, that RxJS just delays the final response not the server call. But I really need to delay the real server call. That wasn't a problem in AngularJS via HttpInterceptor but I can't get it to work. Any ideas?

Thx in advance.

Update:

I already tried the HttpInterceptor but that doesnt work either. I have a CustomHttpClient which puts running request urls in an array and removes them after its done. Some request cannot run in parallel so I've to check the list for pending calls from e.g. /api/somePath. If such an url is in the list the current request has to be delayed. Works fine within the HttpInterceptor of AngularJS.

like image 569
Marsch Avatar asked Dec 24 '22 05:12

Marsch


2 Answers

I like those interceptors, because you can do a lot of magic with them.

Handle the RESPONSE of a http call in the interceptor

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

Handle the REQUEST of a http call in the interceptor for example delaying it.

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

in both cases it´s the same "intercept(...)" Method, but different handling of the "next.handle()".

warm regards

like image 170
JanRecker Avatar answered Dec 25 '22 19:12

JanRecker


If you want to delay the call itself with RxJS you can use timer:

timer(5000)
  .pipe(
    concatMap(() => of(42)),
  )
  .subscribe(...)
like image 22
martin Avatar answered Dec 25 '22 18:12

martin