How to listen HTTP response and apply preloader?
How to listen HTTP response and apply preloader?
I use HTTP library for executing request to server in my SPA like this:
public get(cls: number): Observable<any>
const data =
;
return this.http.post(null, data)
.map(result =>
return result.json().result;
)
.catch(this.handleErrorObservable);
Let's assume we have a preloader service, that is started when request leaves and stops when response comes.
How to bind this service to HTTP? Exactly, I can subscribe on Observer response like:
preloader.start();
get(1).subscribe(data => , error =>
preloader.stop();
);
But it is not fit for me, I want to make this more universal and more abstract
Really good idea, and inject preloader there?
– OPV
Aug 25 at 19:17
Yeah I mean you can do that. You'll just have to check where exactly(for which specific request) you want to start them and where you want to stop the,.
– SiddAjmera
Aug 25 at 19:19
I dont understand is ppreloder directive or what?
– OPV
Aug 25 at 19:27
1 Answer
1
You may want to use ng-http-loader library, to install it:
$ npm install ng-http-loader --save / yarn add ng-http-loader
This package provides an HTTP Interceptor, and some spinner components. The HTTP interceptor listens to all HTTP requests and shows a spinner / loader indicator during pending http requests.
usage:
From your Angular AppModule:
import BrowserModule from '@angular/platform-browser';
import NgModule from '@angular/core';
[...]
import AppComponent from './app.component';
import HttpClientModule from '@angular/common/http'; <============
import NgHttpLoaderModule from 'ng-http-loader'; <============
@NgModule(
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule, <============ (Perform http requests with this module)
NgHttpLoaderModule, <============
],
providers: ,
bootstrap: [AppComponent]
)
export class AppModule
In your app.component.html, simply add:
<ng-http-loader></ng-http-loader>
Here's the full documentation: https://github.com/mpalourdio/ng-http-loader
For some reason, I don't really think using a third party package for this is really worth it. Just increases the bundle size without much added advantage.
– SiddAjmera
Aug 25 at 19:21
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Why don't you use Interceptors?
– SiddAjmera
Aug 25 at 19:16