首页 > 解决方案 > 从共享服务关闭材料对话框

问题描述

在我的 Angular 8 应用程序中,我angular-material dialog用来执行 CRUD 操作。如果我想从同一个组件关闭组件中的对话框,我在该构造函数中将 ref 设置为对话框组件的名称

constructor(
@Inject(MAT_DIALOG_DATA)
public dialogRef: MatDialogRef<AssingTrialRoleComponent>,  //AssingTrialRoleComponent name of class
private store: Store<fromStore.State>
) {

并且为了关闭,我调用this.dialogRef.close();了相同的组件

但现在,我添加@ngrx/store,并在其中@effect检查错误或成功,并调用共享通知服务来显示通知。通过这个共享通知服务,我想要一个关闭的对话框。3

  map(
      () => new actions.LoadUsers(),
      this.notificationService.success("Success, dialog is closed"), 
    ),
    catchError(err => of(this.notificationService.warn(err.error.message)))
   )

如果catchError被触发,对话框需要保持打开状态,如果success我需要从我的共享通知服务中关闭对话框。

这是我的通知服务

export class NotificationPopUpServiceService {
constructor(public snackBar: MatSnackBar) {}

config: MatSnackBarConfig = {
   duration: 3000,
   horizontalPosition: "right",
   verticalPosition: "top"
 };

success(msg) {
   this.config["panelClass"] = ["notification", "success"];
   this.snackBar.open(msg, "", this.config);
   this.dialogRef.close();    <-- this is where I need to close dialog 
}

warn(msg) {
   this.config["panelClass"] = ["notification", "warn"];
   this.snackBar.open(msg, "", this.config);
}
}

我在同一个应用程序上有多个对话框,我想在共享服务中以某种方式知道他们需要在哪个组件中关闭对话框...

如果我在 中触发此服务,请在user.component中关闭此对话框user.component,如果我在中触发服务,请在company.component关闭此对话框中......等等......

有没有办法从另一个服务/组件关闭模式?

谢谢

标签: angular

解决方案


也许每个组件中 NotificationPopUpServiceService 的构造函数的 DI 是解决方案,

在您的服务中:

export class NotificationPopUpServiceService {
constructor(public snackBar: MatSnackBar) {}

config: MatSnackBarConfig = {
   duration: 3000,
   horizontalPosition: "right",
   verticalPosition: "top"
 };

success(msg) {
   this.config["panelClass"] = ["notification", "success"];
   this.snackBar.open(msg, "", this.config);
   this.closingDialogEvent('dialogName');    //is going to close the notification from a specific call
}

warn(msg) {
   this.config["panelClass"] = ["notification", "warn"];
   this.snackBar.open(msg, "", this.config);
}

closingDialogEvent(name:string) {
    this.dialogRef.close(name);
   console.log('event after closing dialog' );
  }
}

推荐阅读