[英]Angular Interceptor Response 302
Can I make a interceptor to catch 302 response in angular, before automatic redirect?在自动重定向之前,我可以制作一个拦截器来捕获 angular 中的 302 响应吗?
How to intercept url redirect in angular response 302如何在angular响应302中拦截url重定向
You should do something like below:你应该做如下的事情:
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:在 app.module.ts 添加以下内容:
It means it will be available throughout the application.这意味着它将在整个应用程序中可用。
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true,
},
],
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.