Search code examples
angularrxjs

Angular 5+ : How to put a delay to a / all HttpClient requests?


I have this code :

this.loading = true;
this.http.get<IUser[]>(Urls.users())
            .subscribe(
                response => {
                    this._values = <IUser[]>response;
                    this.root.next({'users': this._values});
                },
                e => console.log(e),
                () => this.loading = false
            );

The page which is invoking this code has a spinner, which is showing when 'loading' is set to 'true'. But when the request is completed withing 0.5 seconds the spinner is barely shown, and it looks weird on the page.

How can I make this request wait 1 second before completing (without using setTimeout()) ?

Is there a way to delay all http requests without having to modify every code like the code above ?


Solution

  • For latest versions of Angular,you can use:

    import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
    import { Injectable } from '@angular/core';
    import { Observable } from 'rxjs';
    import { delay } from 'rxjs/operators';
    
    @Injectable()
    export class DelayInterceptor implements HttpInterceptor {
      intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log(request);
        return next.handle(request).pipe(delay(5000));
      }
    }
    

    Ref: Wolf359 answer