Reputation: 313
In my angular2 app I want to show a preloader(locking screen) every time an http
request starts and hide it after request ends. The subscribe method allows us to detect when a request is successful, has errors or completes. I think that it`s a bad idea to write code of preloader every time I call subscribe method on the request.
Upvotes: 2
Views: 553
Reputation: 202176
I would extend the Http
class like below and add a service containing an observable / subject to be notified when an HTTP request is 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 it as 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 could be something like that:
export class NotifierService {
notifier:Subject<any> = new Subject();
notifyBeforeRequest() {
notifier.next();
}
}
You can be notified this way:
@Component({
(...)
})
export class SomeComponent {
constructor(private notifyService:NotifierService) {
this.notifyService.notifier.subscribe(() => {
// do something
});
}
}
Upvotes: 2
Reputation: 3520
You can do that in 2 ways
Create a DataService and wrap Http
which will be used to call the API, put your preloader logic in service.
you can use Interceptor
, here is an example here and here
I prefer option 1 which is more extendable, you can control all calls from one place.
Upvotes: 1