Skip to content

Instantly share code, notes, and snippets.

@harbirchahal
Created May 15, 2019 11:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save harbirchahal/84d3d7dd1d0838479d298a06b1c51928 to your computer and use it in GitHub Desktop.
Save harbirchahal/84d3d7dd1d0838479d298a06b1c51928 to your computer and use it in GitHub Desktop.
Request Timeout HTTP Interceptor (Header)
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { RequestTimeoutHttpInterceptor, DEFAULT_TIMEOUT } from './interceptors';
import { AppComponent } from './app.component';
@NgModule({
imports: [
BrowserModule,
HttpClientModule,
],
declarations: [
AppComponent,
],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: RequestTimeoutHttpInterceptor, multi: true },
{ provide: DEFAULT_TIMEOUT, useValue: 5000 },
],
bootstrap: [AppComponent]
})
export class AppModule { }
import { Injectable, InjectionToken, Inject } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { empty, TimeoutError } from 'rxjs';
import { timeout, catchError } from 'rxjs/operators';
export const DEFAULT_TIMEOUT = new InjectionToken<number>('defaultTimeout');
@Injectable({
providedIn: 'root'
})
export class RequestTimeoutHttpInterceptor implements HttpInterceptor {
constructor(
@Inject(DEFAULT_TIMEOUT) protected defaultTimeout: number,
) { }
intercept(req: HttpRequest<any>, next: HttpHandler) {
const modified = req.clone({
setHeaders: { 'X-Request-Timeout': `${this.defaultTimeout}` }
});
return next.handle(modified).pipe(
timeout(this.defaultTimeout),
catchError(err => {
if (err instanceof TimeoutError)
console.error('Timeout has occurred', req.url);
return empty();
})
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment