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





Why don't you use Interceptors?
– SiddAjmera
Aug 25 at 19:16





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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

How do I collapse sections of code in Visual Studio Code for Windows?

Node.js puppeteer - Use values from array in a loop to cycle through pages