Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angular

rxjs

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 ?

like image 596
Wolf359 Avatar asked Apr 30 '18 20:04

Wolf359


People also ask

Is angular HttpClient asynchronous?

1.1 The Angular HTTP ClientThe API is asynchronous. JavaScript is single-threaded. Doing a blocking synchronous HTTP call will otherwise freeze the UI. It supports making HTTP requests (GET, POST, etc.), working with request and response headers, asynchronous programming.

What is HTTP interceptor in angular?

HTTP Interceptors is a special type of angular service that we can implement. It's used to apply custom logic to the central point between the client-side and server-side outgoing/incoming HTTP request and response. Keep in mind that the interceptor wants only HTTP requests. AngularInterceptor.zip.

Is HttpClient observable?

The HttpClient service makes use of observables for all transactions.


2 Answers

Use rxjs/delay:

this.http.get(...).delay(500).subscribe(...);

In Angular 6+:

this.http.get(...).pipe(delay(500)).subscribe(...);
like image 184
Phil Avatar answered Oct 15 '22 16:10

Phil


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);
    }
}
like image 40
Wolf359 Avatar answered Oct 15 '22 15:10

Wolf359