Angular 4:使用HTTP拦截器+RxJS timeout操作符遇问题
Implementing 10-Second Default Timeout for All HTTP Requests in Angular
Got it! Adding a default 10-second timeout to every HTTP request via your existing interceptor is straightforward with RxJS's timeout operator. Here's how to update your interceptor to include this functionality:
Complete Interceptor Code
import { Injectable } from '@angular/core'; import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http'; import { Observable } from 'rxjs'; import { timeout, catchError } from 'rxjs/operators'; import { throwError } from 'rxjs'; @Injectable() export class HttpConfigInterceptor implements HttpInterceptor { intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { // Your existing header modification logic (keep what you already have) const modifiedRequest = request.clone({ headers: request.headers .set('Content-Type', 'application/json') // Add any other custom headers here }); // Apply 10-second timeout to the request stream return next.handle(modifiedRequest).pipe( timeout(10000), // 10000ms = 10 seconds // Optional: Handle timeout errors globally catchError(error => { if (error.name === 'TimeoutError') { console.error('Request timed out after 10 seconds'); // You could also redirect to an error page or show a toast here } // Re-throw the error so components can handle it too if needed return throwError(() => error); }) ); } }
Key Details:
- Cloning the Request: We clone the original request to modify headers (as you were already doing) because HTTP requests are immutable in Angular.
- Timeout Operator: The
timeout(10000)operator will automatically cancel the request if it doesn't complete within 10 seconds, and throw aTimeoutError. - Error Handling: The optional
catchErrorblock lets you handle timeout errors globally (like logging or showing a user message). You can skip this if you prefer to handle errors in individual service calls instead.
Don't Forget to Register the Interceptor!
Make sure your interceptor is provided in your app module so Angular uses it for all requests:
// In app.module.ts import { HTTP_INTERCEPTORS } from '@angular/common/http'; import { HttpConfigInterceptor } from './path-to-your-interceptor-file'; @NgModule({ providers: [ { provide: HTTP_INTERCEPTORS, useClass: HttpConfigInterceptor, multi: true // Important: Allows multiple interceptors to run } ] }) export class AppModule { }
Note for Older RxJS Versions
If you're using RxJS 5 or earlier, the import syntax is slightly different:
// RxJS 5 imports import 'rxjs/add/operator/timeout'; import 'rxjs/add/operator/catch';
And you'd chain the operators directly instead of using pipe():
return next.handle(modifiedRequest) .timeout(10000) .catch(error => { /* handle error */ });
内容的提问来源于stack exchange,提问作者Fel
相关产品推荐
相关产品推荐

