angular - How to add preloader to every http request(angular2)? -
in angular2 app want show preloader(locking screen) every time http
request starts , hide after request ends. subscribe method allows detect when request successful, has errors or completes. think it`s bad idea write code of preloader every time call subscribe method on request.
- how can detect request starts/ends(except in subscribe method)?
- what way add preloader every request?
i extend http
class below , add service containing observable / subject notified when http request executed
export class customhttp extends http { constructor(backend: connectionbackend, defaultoptions: requestoptions, private _notifierservice:notifierservice) { super(backend, defaultoptions); } request(url: string | request, options?: requestoptionsargs): observable<response> { this._notifierservice.notifybeforerequest(); return super.request(url, options); } get(url: string, options?: requestoptionsargs): observable<response> { this._notifierservice.notifybeforerequest(); return super.get(url, options); } (...) }
register described below:
bootstrap(appcomponent, [http_providers, { provide: http, usefactory: (backend: xhrbackend, defaultoptions: requestoptions, notifyservice:notifierservice) => { return new customhttp(backend, defaultoptions, notifyservice); }, deps: [xhrbackend, requestoptions, notifierservice] } ]);
the service implement that:
export class notifierservice { notifier:subject<any> = new subject(); notifybeforerequest() { notifier.next(); } }
you can notified way:
@component({ (...) }) export class somecomponent { constructor(private notifyservice:notifierservice) { this.notifyservice.notifier.subscribe(() => { // }); } }
Comments
Post a Comment