0

我在角度使用以下全局ErrorHandler:

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {

  constructor(private errorService: ErrorService, private messageNotificationService: MessageNotificationService) { }

  handleError(error: Error | HttpErrorResponse | any) {
      // handle api server error
    }
    else {
      // client Error
      message = this.errorService.getClientErrorMessage(error);
      this.messageNotificationService.showError(message);
    }
  }
}

以及以下带有小吃店的 NotificationService

@Injectable({
  providedIn: 'root'
})
export class MessageNotificationService {

  constructor(
    public snackBar: MatSnackBar,
    private zone: NgZone) { }

  showError(message: string): void {
    this.zone.run(() => {
      this.snackBar.open(message, 'X', { panelClass: ['error'], verticalPosition: "top", horizontalPosition: "center" });
    });
  }
}

当循环中发生有角度的客户端错误/异常时,会重叠显示几个快餐栏:

在此处输入图像描述

有没有办法将小吃店的显示减少到 1 次?有没有办法阻止错误/异常传播?

4

1 回答 1

0

您可以维护一个count变量,并执行以下操作:

@Injectable({
  providedIn: 'root'
})
export class MessageNotificationService {

 count = 0;
 snackBarRef;

 constructor(public snackBar: MatSnackBar,
          private zone: NgZone) {
 }

 showError(message: string): void {

   this.count++;

   if (this.count === 1) {
      this.zone.run(() => {
        this.snackBarRef = this.snackBar.open(message, 'X', {
        panelClass: ['error'],
        verticalPosition: "top",
        horizontalPosition: "center"
       });
     });
   }

  this.snackBarRef.afterDismissed().subscribe(() => {
   this.count = 0;
  });

  }
}
于 2021-10-23T07:04:40.967 回答