From 49b79b617d5174dad67b3ef45b7ff6083120d9ea Mon Sep 17 00:00:00 2001 From: "swapnil.verma" Date: Wed, 26 Jun 2024 11:43:53 +0530 Subject: [PATCH] Updated UnsavedChangesGuard to be a functional guard --- .../auth/guard/auth-guard-sso-role.service.ts | 1 + .../unsaved-changes.guard.ts | 38 ++++++++----------- 2 files changed, 17 insertions(+), 22 deletions(-) diff --git a/lib/core/src/lib/auth/guard/auth-guard-sso-role.service.ts b/lib/core/src/lib/auth/guard/auth-guard-sso-role.service.ts index 3069421612e..653efaf5109 100644 --- a/lib/core/src/lib/auth/guard/auth-guard-sso-role.service.ts +++ b/lib/core/src/lib/auth/guard/auth-guard-sso-role.service.ts @@ -26,6 +26,7 @@ const dialog = inject(MatDialog); /** * Function to validate if the current user has/does not have the provided set of roles + * * @param rolesToCheck list of roles that the user needs to be checked * @param excludedRoles list of roles that the user should not have * @returns boolean flag corresponding to whether the user has/does not have the provided set of roles/excluded roles diff --git a/lib/core/src/lib/dialogs/unsaved-changes-dialog/unsaved-changes.guard.ts b/lib/core/src/lib/dialogs/unsaved-changes-dialog/unsaved-changes.guard.ts index d18353b3c2c..48ba9931907 100644 --- a/lib/core/src/lib/dialogs/unsaved-changes-dialog/unsaved-changes.guard.ts +++ b/lib/core/src/lib/dialogs/unsaved-changes-dialog/unsaved-changes.guard.ts @@ -15,8 +15,8 @@ * limitations under the License. */ -import { Injectable } from '@angular/core'; -import { CanDeactivate } from '@angular/router'; +import { inject } from '@angular/core'; + import { Observable } from 'rxjs'; import { MatDialog } from '@angular/material/dialog'; import { UnsavedChangesDialogComponent } from './unsaved-changes-dialog.component'; @@ -24,24 +24,18 @@ import { tap } from 'rxjs/operators'; /** * Guard responsible for protecting leaving page with unsaved changes. + * + * @returns boolean | Observable flag indicating whether user has unsaved changes or not */ -@Injectable({ - providedIn: 'root' -}) -export class UnsavedChangesGuard implements CanDeactivate { - unsaved = false; - - constructor(private dialog: MatDialog) {} - - /** - * Allows to deactivate route when there is no unsaved changes, otherwise displays dialog to confirm discarding changes. - * - * @returns boolean | Observable true when there is no unsaved changes or changes can be discarded, false otherwise. - */ - canDeactivate(): boolean | Observable { - return this.unsaved ? - this.dialog.open(UnsavedChangesDialogComponent, { - maxWidth: 346 - }).afterClosed().pipe(tap((confirmed) => this.unsaved = !confirmed)) : true; - } -} +export const UnsavedChangesGuard = (): boolean | Observable => { + let unsaved = false; + const dialog = inject(MatDialog); + return unsaved + ? dialog + .open(UnsavedChangesDialogComponent, { + maxWidth: 346 + }) + .afterClosed() + .pipe(tap((confirmed) => (unsaved = !confirmed))) + : true; +};