You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 2拦截器错误处理中如何实现指定页面重定向?

Solution for Redirecting on Specific Error in Angular HttpInterceptor

Got it, let's get this sorted out for you! Here's how to implement the redirect when that specific error message comes back from the server:

Step 1: Update Your Interceptor Code

First, you'll need to inject Angular's Router service into your interceptor (since we need it to handle navigation). Also, note that in RxJS 6+, the do operator was renamed to tap—so we'll use that to stay up-to-date.

Here's the revised code:

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { tap, catchError } from 'rxjs/operators';
import { Router } from '@angular/router';

@Injectable()
export class YourInterceptorName implements HttpInterceptor {

  // Inject Router into the constructor
  constructor(private router: Router) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
      tap(event => {
        // Log events if you still need to
        console.log('EVENT:', event);
      }),
      catchError((err: HttpErrorResponse) => {
        const message = err.error?.message; // Use optional chaining to avoid null errors
        if (message === 'You need to activate your account!') {
          // Redirect to the not-activated page
          this.router.navigate(['/auth/not-activated']);
        }
        // Re-throw the error so components subscribing to the request can still handle it
        return throwError(() => err);
      })
    );
  }
}

Key Points Explained:

  • Injecting Router: We add private router: Router to the constructor so we can access Angular's navigation methods.
  • RxJS Operators: We switched from do to tap (modern RxJS syntax) and use catchError to properly handle errors (this is better than the error callback in tap/do for error handling logic).
  • Optional Chaining: err.error?.message prevents errors if err.error is null or undefined.
  • Re-throwing Errors: After handling the redirect, we return throwError(() => err) so any component that subscribed to the original HTTP request can still catch and handle the error if needed (don't skip this, otherwise the error will be swallowed).

If You're Using RxJS 5.x (Older Versions)

If you're stuck on an older RxJS version, you can keep using do but structure the error handling like this:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  return next.handle(req).do(
    event => console.log('EVENT:', event),
    (err: HttpErrorResponse) => {
      const message = err.error.message;
      if (message === 'You need to activate your account!') {
        this.router.navigate(['/auth/not-activated']);
      }
      // For RxJS 5, re-throw with Observable.throw(err)
      return Observable.throw(err);
    }
  );
}

Just make sure you've registered your interceptor in your Angular module's providers array so it actually runs!

内容的提问来源于stack exchange,提问作者User

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:09:41