gpt4 book ai didi

angular - HttpErrorInterceptor无法在Angular中重定向

转载 作者:行者123 更新时间:2023-12-03 08:09:00 25 4
gpt4 key购买 nike

我正在尝试制作一个全局错误拦截器,以便对每个错误都将使用error=true查询参数重定向到主页。它会以某种方式捕获错误,将其记录下来,但不会重定向。我究竟做错了什么?
HttpErrorInterceptor:

@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {

constructor(private router: Router) {
}

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request)
.pipe(
catchError((error: HttpErrorResponse) => {
let errorMsg = '';
if (error.error instanceof ErrorEvent) {
errorMsg = `Error: ${error.error.message}`;
} else {
errorMsg = `Error Code: ${error.status}, Message: ${error.message}`;
}
const urlParams = new URLSearchParams(window.location.search);
this.router.navigate(['main'], {queryParams: {error: true, sesskey: urlParams.get('sesskey')}});
console.log(errorMsg);
return throwError(errorMsg);
})
)
}
}
app.module.ts:
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: HttpErrorInterceptor,
multi: true
},

最佳答案

我认为这可行,您如何测试它
对我来说,它像这样

export class AppComponent {

constructor(private http: HttpClient) {
this.getData();
}

getData() {
const url = 'Fake url';
return this.http.get(url).subscribe();
}
}

关于angular - HttpErrorInterceptor无法在Angular中重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64571903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com