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

  • I ended up using an HttpInterceptor + delay operator (thanks @Faisal) : It is the solution to my question, but it's not necessarily the best user experience. Please see @AlexanderLeonov 's comment on this.

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