如何在 http 错误时重定向到另一个页面?

How to redirect to to another page on http error?

我在派生自 Angular HttpInterceptor 的 class 中有以下代码:

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()])
    }

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;
}

如何实现http错误重定向?

你可以让你的 handleError 函数 return 类型为 void(它的目标是导航)。

并在 catchError

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

如果您想发送到 angular 的错误页面,只需在您的服务中注入路由器并导航发送 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);
  }

你的error.component

@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))
  }

}

查看 stackblitz

这是每个未排序的请求都将重定向到登录页面的示例

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;
          }
        }
      }));
  }
}

并在 app.module.ts 文件中添加 { provide: HTTP_INTERCEPTORS, useClass: UnAuthorizedInterceptor, multi: true } 作为提供商