angularangular-httpangular-http-interceptorsangular-httpclient

How to Show spinner for every HTTP requests in angular 5?


i am new to angular 5 . How to code a common function to show spinner for every HTTP request in angular 5.Please help me to implement this.


Solution

  • You can use Angular HttpInterceptor to show a spinner for all your requests, Here's a good medium article on how to implement an http interceptor

    Also, you will have to create a spinner service/module and inject it in your http interceptor. Finally, in your intercept method you can use the finally rxJs method to stop your spinner. Here's a simple implementation:

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        this.spinnerService.start();
        return next.handle(req).finally(res => this.spinnerService.stop() );
    }
    

    Enjoy!

    Bonus: Here's a spinner service implementation example