app.ts
//our root app component
import {Component, Inject, Injectable, InjectionToken, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {HttpClientModule, HttpHeaders, HttpClient, HTTP_INTERCEPTORS, HttpInterceptor, HttpRequest, HttpHandler} from '@angular/common/http'
import { Observable } from 'rxjs/Observable';
import { TimeoutError } from 'rxjs/util/TimeoutError';
import 'rxjs/add/operator/timeout';
const DEFAULT_TIMEOUT = new InjectionToken<number>('defaultTimeout');
const defaultTimeout = 10000;
@Injectable()
export class TimeoutInterceptor implements HttpInterceptor {
constructor(@Inject(DEFAULT_TIMEOUT) protected defaultTimeout) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const timeout = Number(req.headers.get('timeout')) || this.defaultTimeout;
req.headers = req.headers.delete('timeout');
return next.handle(req).timeout(timeout);
}
}
@Component({
selector: 'my-app',
template: ``,
})
export class App {
name:string;
constructor(http: HttpClient) {
http.get('test.json', { headers: new HttpHeaders({ timeout: `${10}` }) })
.subscribe(null, err => {
console.log('custom short timeout, err instanceof TimeoutError is %s', err instanceof TimeoutError)
});
http.get('test.json', { headers: new HttpHeaders({ timeout: `${20000}` }) })
.subscribe(console.log('custom long timeout'));
http.get('test.json')
.subscribe(console.log('default timeout'));
}
}
@NgModule({
imports: [ BrowserModule, HttpClientModule ],
providers: [
[{ provide: HTTP_INTERCEPTORS, useClass: TimeoutInterceptor, multi: true }],
[{ provide: DEFAULT_TIMEOUT, useValue: defaultTimeout }]
],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}