Search code examples
angularangular-materialngrx-storengrx-effects

Close dialog component from effect


I need to close angular material dialog from @ngrx/effect

here is my code

import { MatDialogRef, MatDialog } from "@angular/material/dialog";
import { AddComponent } from "./../../add/add.component";

@Injectable()
export class UserEffects {
@Effect()
addNewUser$ = this.actions$.pipe(
    ofType(actions.UserActionTypes.addNewUser),
         mergeMap((user: actions.addNewUser) =>
             this.userService.createUser(user.user).pipe(
                map(() => {
                  new actions.LoadUsers(),
                  this.notificationService.success("User added successfully!");
                  this.dialogRef.close();     <------ // here i try to close
                }),
              catchError(error => of(new actions.Error(error.error)))
            )
        )
    );

constructor(
    private actions$: Actions<actions.UserActions>,
    private userService: UserService,
    private notificationService: NotificationPopUpServiceService,
    public dialogRef: MatDialogRef<AddComponent>
) {}
}

And with this i get error

main.ts:13 NullInjectorError: R3InjectorError[EffectsRootModule -> InjectionToken ngrx/effects: Root Effects -> UserEffects -> MatDialogRef -> MatDialogRef -> MatDialogRef]: NullInjectorError: No provider for MatDialogRef!

What is the best way to close material-dialog from effect or from service? Because we always need to set a name for the dialog component?

Thank you


Solution

  • I think I find a solution, but If there something better pls, let me know... I add this.dialogRef.closeAll()

    class UserEffects {
      constructor(
        private actions$: Actions,
        private dialogRef: MatDialog,
        private notificationService: NotificationService,
      ) {}
    
      @Effect()
          addNewUser$ = this.actions$.pipe(
          ofType(actions.UserActionTypes.addNewUser),
              mergeMap((user: actions.addNewUser) =>
                this.userService.createUser(user.user).pipe(
                  map(() => {
                    new actions.LoadUsers(),
                    this.notificationService.success("User added successfully!");
                    this.dialogRef.closeAll();    <--- //this is the key
                  }),
          catchError(error => of(new actions.Error(error.error)))
        )
      ));
    }
    

    EDIT:

    modal is closed, but I get error

    core.js:6014 ERROR Error: Effect "UserEffects.addNewUser$" dispatched an invalid action: undefined

    TypeError: Actions must be objects

    Any help? Thnx