Reputation: 59
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.
Upvotes: 5
Views: 11095
Reputation: 1847
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
Upvotes: 8
Reputation: 96889
If you want to delay the call itself with RxJS you can use timer
:
timer(5000)
.pipe(
concatMap(() => of(42)),
)
.subscribe(...)
Upvotes: 3
Reputation: 7165
Start with a different observable (in this case a timer observable) and switch to your http client observable:
timer(1000).pipe(
switchMap(() => this.http.get('')),
)
.subscribe();
or
of(null).pipe(
delay(1000),
switchMap(() => this.http.get('')),
)
.subscribe();
Upvotes: 2
Reputation: 10137
Well you can, again, use a HttpInterceptor
from @angular/common/http
do to that for you.
Or just:
Observable.timer(5000).pipe(tap(
// do your stuff
))
Upvotes: 1
Reputation: 2684
You can use RxJS Observable.timer
let myRequest = this.http.get(...);
let pollingSubscription = myRequest
.expand(() => Observable.timer(5000).flatMap(() => myRequest))
.subscribe();
Upvotes: 0