简体   繁体   中英

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

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,
    },
  ],

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM