我试图在应用程序中出现错误时显示错误组件。我使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
}
]
})
答案 0 :(得分:2)
您的错误响应是 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
上的错误。
类型“可观察>”上不存在属性“ catchError”。
因此将代码更改为此
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);
})