Angular 如何重定向到http错误上的其他页面?

Angular 如何重定向到http错误上的其他页面?,angular,typescript,angular-http-interceptors,Angular,Typescript,Angular Http Interceptors,我在从Angular HttpInterceptor派生的类中有以下代码: handleError(error: unknown): Promise<boolean> { if (error instanceof HttpErrorResponse) { return this.router.navigate([NOT_FOUND_URL, this.errorDescriptionProvider.getHttpErrorDescriptio

我在从Angular HttpInterceptor派生的类中有以下代码:

handleError(error: unknown): Promise<boolean> {
        if (error instanceof HttpErrorResponse) {
            return this.router.navigate([NOT_FOUND_URL, this.errorDescriptionProvider.getHttpErrorDescription(error)]);           
        }
        else
            return this.router.navigate([NOT_FOUND_URL, this.errorDescriptionProvider.getUnspecifiedNetworkErrorDescription()])
    }
handleError(错误:未知):承诺{
if(HttpErrorResponse的错误实例){
返回this.router.navigate([NOT_FOUND_URL,this.errorDescriptionProvider.getHttpErrorDescription(error)];
}
其他的
返回此.router.navigate([未找到\u URL,此.errorDescriptionProvider.getUnspecifiedNetworkErrorDescription()]))
}

intercept(req: HttpRequest<T>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    const stream =  next
        .handle(req)
        .pipe
        (
           catchError(x => from(this.handleError(x)))              
        );

        //Error that boils down to: is not assignable to Observable<HttpEvent<unknow>> since its type is Observable<boolean |....>
        return  stream;
}
intercept(req:HttpRequest,next:HttpHandler):可观察{
常量流=下一个
.句柄(req)
管
(
catchError(x=>from(this.handleError(x)))
);
//错误归结为:由于其类型是可观察的,所以不可分配给可观察的
回流;
}

如何在http错误上实现重定向?

您可以使handleError函数返回类型为void(其目标是导航)

而且是错误的

  catchError(err => {
    if (err instanceof HttpErrorResponse) {
      //call your handle error function
       handleError(err);
    }
    return throwError(err);
  }),

如果您想发送到服务器的errorPage,只需在服务中插入路由器,并在navigate.extra中导航发送数据

愚蠢的服务

  getData()
  {
    return throwError({error:"NotExist"}).pipe(catchError(x=>{
      return this.error(x)
    }))

  }
  error(x):Observable<any>
  {
    console.log(x)
    this.router.navigate(['/error'],{ state: { error: x } })
    return of(null);
  }
getData()
{
返回抛出器错误({error:“NotExist”}).pipe(catchError(x=>{
返回此错误。错误(x)
}))
}

错误(x):可观察的

下面是一个示例,说明每个非常规请求都将重定向到登录页面

import{HttpErrorResponse,HttpEvent,HttpHandler,HttpInterceptor,HttpRequest}来自“@angular/common/http”;
从“@angular/core”导入{Injectable}”;
从“rxjs/Rx”导入{Observable};
从“@angular/Router”导入{Router}”;
从“rxjs/internal/operators”导入{tap};
@可注射()
导出类UnAuthorizedInterceptor实现HttpInterceptor{
构造函数(专用路由器:路由器){}
拦截(请求:HttpRequest,下一步:HttpHandler):可观察{
返回next.handle(request).pipe(点击(()=>{},
(错误:任意)=>{
if(HttpErrorResponse的错误实例){
如果((err.status==401)| |(err.status==403)){
this.router.navigate(['/login']);
}否则{
返回;
}
}
}));
}
}

并在app.module.ts文件中添加
{provide:HTTP_拦截器,useClass:UnAuthorizedInterceptor,multi:true}作为提供程序

您可以在stackbiltz中共享它,因为这样更容易调试吗
@Component({
  selector: 'error',
  template: `<h1>ERROR</h1>
  <pre>{{ state$ | async | json }}</pre>
  `,
  styles: [`h1 { font-family: Lato; }`]
})
export class ErrorComponent implements OnInit  {
private state$: Observable<object>;

  constructor(public activatedRoute: ActivatedRoute) { }
    ngOnInit() {
      this.state$ = this.activatedRoute.paramMap
      .pipe(map(() => window.history.state))
  }

}
import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs/Rx";
import { Router } from "@angular/router";
import { tap } from "rxjs/internal/operators";


@Injectable()
export class UnAuthorizedInterceptor implements HttpInterceptor {
  constructor(private router: Router) { }
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(tap(() => { },
      (err: any) => {
        if (err instanceof HttpErrorResponse) {
          if ((err.status === 401) || (err.status === 403)) {
            this.router.navigate(['/login']);
          } else {
            return;
          }
        }
      }));
  }
}