使用角度小吃栏来处理错误,但我已经在其拦截器中处理了错误

问题描述 投票:0回答:1

我想使用小吃店向用户显示错误,我想知道我是否必须在订阅方法中使用错误才能使用小吃店?有什么方法可以不在订阅方法中使用错误并通过小吃店显示错误? 这是我的 http 错误捕获拦截器:

export const httpErrorInterceptor: HttpInterceptorFn = (req, next) => {
  return next(req).pipe(
    catchError((error: HttpErrorResponse) => {
      return throwError(() => error);
    })
  );
};

这是我的订阅方法,它从服务中订阅并发出值:

  login(): void {
    let userInput: UserLogin = {
      email: this.EmailCtrl.value,
      password: this.PasswordCtrl.value
    }

    this.accountService.login(userInput).subscribe({
      next: () => {
        this.router.navigateByUrl('/');

        this.snackBar.open('Login Successful', 'Close', {
          duration: 3000
        });
      },
      error: () => {
        this.snackBar.open('Login Failed', 'Close', {
          duration: 3000
        });
      }
    });
  }

有没有一种方法可以使用小吃栏来处理错误,并且不在登录方法中使用错误?

angular error-handling angular-material angular-http-interceptors
1个回答
0
投票

您的 HTTP 拦截器是无操作的。它所做的只是捕获并重新抛出相同的异常,没有任何副作用。您可以将其删除,而无需更改您的应用程序。

为了实现您的目标,您可以使用

ErrorHandler
定义全局错误处理程序。

您可以将此文件命名为

src/app/global-error-handler.ts

import { ErrorHandler, Injectable, NgZone } from "@angular/core";
import { MatSnackBar } from "@angular/material/snack-bar";

@Injectable({
  providedIn: 'root'
})
export class GlobalErrorHandler implements ErrorHandler {
  constructor(
    private _snackBar: MatSnackBar,
    private _zone: NgZone,
  ) { }

  handleError(error: any): void {
    this._zone.run(() => {
      this._snackBar.open(error, 'Close', { duration: 3000 });
    });
  }
}

请注意,

NgZone
用于修复
MatSnackBar
的定位问题。

您还需要添加提供商:

{ provide: ErrorHandler, useClass: GlobalErrorHandler }

对于独立应用程序,您可以将其添加到

src/app/app.config.ts

export const appConfig: ApplicationConfig = {
  providers: [
    { provide: ErrorHandler, useClass: GlobalErrorHandler }
  ]
};

否则将其添加到根模块中:

@NgModule({
    // ...
    providers: [
        { provide: ErrorHandler, useClass: GlobalErrorHandler },
    ]
})
export class AppModule { }
© www.soinside.com 2019 - 2024. All rights reserved.