【问题标题】:Angular: multiple material snackbar in global ErrorHandlerAngular:全局 ErrorHandler 中的多种材质小吃吧
【发布时间】:2021-12-09 06:10:10
【问题描述】:

我在 Angular 中使用以下全局 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" });
    });
  }
}

当循环中发生 Angular 客户端错误/异常时,会重叠显示多个小吃栏:

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

【问题讨论】:

  • duration: 3000 ,设置关闭snackbar的持续时间,然后在关闭之前的snackbar之前打开新snackbar的那一刻自动关闭。参见参考文献material.angular.io/components/snack-bar/overview#dismissal
  • @GaurangDhorda:感谢您的回答。问题是小吃店不再反应。它不再关闭。也可以通过输入持续时间或单击 。可能是因为错误处理程序在无限循环中被调用。

标签: angular typescript angular-material snackbar angular-errorhandler


【解决方案1】:

您可以维护一个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;
  });

  }
}

【讨论】:

  • 感谢您的回答。问题是snackbar(在无限循环的情况下)不再反应。它不再关闭。也可以通过输入持续时间或单击即使错误受限于计数器 = 1。
  • 你必须解决你为什么进入无限循环。
猜你喜欢
  • 2018-11-16
  • 2018-07-03
  • 2016-03-17
  • 2018-09-12
  • 1970-01-01
  • 2021-05-13
  • 1970-01-01
  • 2020-09-07
  • 2018-10-25
相关资源
最近更新 更多