angularinterceptorhttp-status-code-302

Angular Interceptor Response 302


Can I make a interceptor to catch 302 response in angular, before automatic redirect?

How to intercept url redirect in angular response 302


Solution

  • You should do something like below:

    1. Create a folder in src, ex: interceptors;
    2. Create a file inside it, ex.: auth.ts;

    File content:

    Please see the comments.

     @Injectable()
    export class AuthInterceptor implements HttpInterceptor {
     // Inject dependencies as you need
      constructor(private someService: someService, private route: Router) {}
    
      intercept(
        req: HttpRequest<any>,
        next: HttpHandler
      ): Observable<HttpEvent<any>> {
            
        return next.handle().pipe(
          tap((resp) => {
            if (resp instanceof HttpResponse) {
              if (resp.status === 302) {
                // here you can implement your logic, or simply redirect as below
                this.route.navigate(['/someroute']);
              }
            }
          }),
           
          // You can also check for other errors as follows:
          catchError((err: HttpErrorResponse) => {
            let errorMsg = err.error.message;
    
            if (err instanceof HttpErrorResponse) {
              if (err.status == 401) {
                // here you can implement your logic, or simply redirect as below
                this.route.navigate(['/']);
                
              }
            }
    
            if (err.error instanceof ErrorEvent) {
              console.log('Client side error caught in interceptor');
            } else {
              console.log('Server side error caught in interceptor');
            }
            return throwError(() => new Error(errorMsg));
          })
        );
      }
    }
    

    In app.module.ts add the following:

    It means it will be available throughout the application.

    providers: [
        {
          provide: HTTP_INTERCEPTORS,
          useClass: AuthInterceptor,
          multi: true,
        },
      ],