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 ?
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.
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.
The HttpClient service makes use of observables for all transactions.
Use rxjs/delay:
this.http.get(...).delay(500).subscribe(...);
In Angular 6+:
this.http.get(...).pipe(delay(500)).subscribe(...);
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With