i did an interceptor service to see if the error of a request is 401 (unAuthorized) to go to login page with show and hide loading globally also.
But still need to add the header globally with this service (interceptor-service) instead of add header on every request .
second i need also to add timeout(30000) if the request didn’t reply a response this 30 seconds,
i tried it manually on every request it worked but i faced a issue with hideLoadding because i configure the loading also globally.
interceptor-service code:
import {
Http,
ConnectionBackend,
RequestOptions,
RequestOptionsArgs,
Response,
Headers
} from '@angular/http';
import 'rxjs/add/operator/map';
import {Observable} from 'rxjs/Observable';
import {Events} from 'ionic-angular';
import {LoaderService} from '../providers/loader.service';
export class HttpInterceptor extends Http {
public loaderService: LoaderService
constructor(backend: ConnectionBackend,
defaultOptions: RequestOptions,
public events: Events) {
super(backend, defaultOptions);
}
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
return this.intercept(super.get(url, options));
}
post(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> {
return this.intercept(super.post(url, body, this.getRequestOptionArgs(options)));
}
getRequestOptionArgs(options?: RequestOptionsArgs): RequestOptionsArgs {
if (options == null) {
options = new RequestOptions();
}
if (options.headers == null) {
options.headers = new Headers();
}
options.headers.append('Content-Type', 'application/json');
return options;
}
intercept(observable: Observable<Response>): Observable<Response> {
this.events.publish('showLoader');
return observable
.catch(
(err) => {
if (err.status == 401) {
this.events.publish('unAuthorizedRequest', err);
this.events.publish('hideLoader');
return Observable.empty();
} else {
this.events.publish('hideLoader');
return Observable.throw(err);
}
})
.do(
() => {
this.events.publish('hideLoader');
return Observable.empty();
},
() => {
this.events.publish('hideLoader');
return Observable.empty();
}
);
}
}
in the app component:
this.events.subscribe('unAuthorizedRequest', (err) => {
if (!_.endsWith(err.url, '/token')) {
this.nav.setRoot(LoginPage);
}
});
this.events.subscribe('showLoader', () => {
this.numberOfLoading = this.numberOfLoading + 1;
if(this.numberOfLoading === 1){
this.loader = this.loaderService.presentLoading();
}
});
this.events.subscribe('hideLoader', () => {
if(this.numberOfLoading === 1){
this.loader.dismiss();
this.numberOfLoading = 0;
}
if(this.numberOfLoading > 0){
this.numberOfLoading = this.numberOfLoading - 1;
}
});
so anyone know how to set the header globally and the timeout