Reputation: 2496
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:
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;
}
});
Upvotes: 4
Views: 1223
Reputation: 202156
To handle timeout globally, you can leverage the timeout
operator directly on your observable this way:
intercept(observable: Observable<Response>): Observable<Response> {
this.events.publish('showLoader');
return observable
.timeout(2000, new Error('delay exceeded')) // <-------
.catch( ... );
}
Regarding adding a header globally, you can leverage your getRequestOptionArgs
method.
See this article for more details:
Upvotes: 3