首页 > 解决方案 > 如何在 Angular 的 http 服务中添加错误页面重定向

问题描述

我想在我的 api 调用服务中为 400 错误请求添加错误页面重定向:我的代码如下:

服务.ts:

    getIncidents(customerId): Observable<any> {
       return this.http.get<any>(this.incidentApiUrl + "?customer_id=" + customerId)
          .pipe(
            catchError(this.handleError)
          );
      }

   private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      console.log(error.error.message)

    } else {
      console.log(error.status)
    }
    return throwError(
      console.log('Something is wrong!'));
  };

}

我在哪里可以把重定向放在这里?

标签: angular

解决方案


您应该创建一个全局错误处理程序。我是这样实现的。

import { ErrorHandler, Injectable, Injector } from '@angular/core';

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
    constructor(private logService: LoggerService, private router : Router) {

    }
    handleError(error) {

    if(error.status == 404){
      this.router.navigate(['/error-page']);
    }
  }
}

并添加到提供者NgModule

  provide: LocationStrategy, useClass: HashLocationStrategy},
   {
        provide: ErrorHandler, 
        useClass: GlobalErrorHandler
   }

推荐阅读