[英]Angular Interceptor Response 302
在自動重定向之前,我可以制作一個攔截器來捕獲 angular 中的 302 響應嗎?
如何在angular響應302中攔截url重定向
你應該做如下的事情:
文件內容:
請看評論。
@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));
})
);
}
}
在 app.module.ts 添加以下內容:
這意味着它將在整個應用程序中可用。
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true,
},
],
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.