norweny
norweny

Reputation: 313

How to add preloader to every http request(angular2)?

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.

  1. How can I detect that a request starts/ends(except in subscribe method)?
  2. What is a good way to add preloader to every request?

Upvotes: 2

Views: 553

Answers (2)

Thierry Templier
Thierry Templier

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

Saqueib
Saqueib

Reputation: 3520

You can do that in 2 ways

  1. Create a DataService and wrap Http which will be used to call the API, put your preloader logic in service.

  2. 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

Related Questions