gpt4 book ai didi

javascript - 当 Angular 6 出现任何错误时如何显示错误分量?

转载 作者:行者123 更新时间:2023-11-30 14:25:19 24 4
gpt4 key购买 nike

我试图在应用程序出现错误时显示错误组件。我创建了 interceptor 来检查是否有任何错误是服务响应。如果是,它将重定向到 error 组件,但目前它没有重定向,为什么这是我的代码 https://stackblitz.com/edit/angular-ctwnid?file=src%2Fapp%2Ferror.intercepter.ts

import { Injectable } from '@angular/core';
import { HttpEvent, HttpErrorResponse, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';

import {catchError, map} from 'rxjs/operators';


@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private router: Router) {}

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).catchError(
(err: HttpErrorResponse) => {
if (err.status === 401) {
this.router.navigate(['/error']);
}
return Observable.throw(err);
}
);
}
}

@NgModule({
imports: [ BrowserModule,
RouterModule.forRoot(routes),
HttpClientModule,FormsModule ],
declarations: [ AppComponent,
HelloComponent ,ErrorComponent],
bootstrap: [ AppComponent ],
providers: [TestService,TestResolver,
{
provide: HTTP_INTERCEPTORS,
useClass: ErrorInterceptor,
multi: true
}

]
})

最佳答案

您的错误响应是 404 而不是 401 检查控制台中的 err

return next.handle(req).catchError(
(err: HttpErrorResponse) => {
console.log(err, err.status); //<==== check here it gives err.status is 404 not 401 as you posted
if (err.status === 404) {
this.router.navigate(['/error']);
}
return Observable.throw(err);
}
);

使用pipe 处理catchError 上的错误。

Property 'catchError' does not exist on type 'Observable>'.

所以把代码改成这样

return next.handle(req).pipe(catchError(  //<==== add pipe here
(err: HttpErrorResponse) => {
console.log(err, err.status); //<==== check here it gives err.status is 404 not 401 as you posted
if (err.status === 404) {
this.router.navigate(['/error']);
}
return Observable.throw(err);
})

关于javascript - 当 Angular 6 出现任何错误时如何显示错误分量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52034417/

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