Close material dialog from shared service

1.6k views Asked by At

In my Angular 8 app I use angular-material dialog to do the CRUD operations. If I want to close the dialog in component from the same component, I set ref in that constructor to name of dialog component

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

and for close, I call this.dialogRef.close(); in same component

But now, I add @ngrx/store, and in @effect I check for error or success and call a shared notification service to show a notification. From this shared notification service, I want a close dialog.3

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

If catchError is triggered, dialog box need to stay open, if success I need to close the dialog from my shared notification service.

here is my notification service

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);
}
}

I have multiple dialog boxes on the same app, and I want somehow know in shared service in which component they need to close dialog...

If I trigger this service in user.component, close this dialog in user.component, if I trigger service in company.component close this dialog....etc....

Is there any way to close modal from another service/component?

thnx

1

There are 1 answers

7
Youssef Tounoussi On

Maybe the DI by constructor of NotificationPopUpServiceService in each component is the solution,

And inside your service :

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' );
  }
}