-
-
Save space11/e3958504ebf160153275517699baf3f3 to your computer and use it in GitHub Desktop.
Request Timeout HTTP Interceptor (Header)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 { } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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