Skip to content

Commit

Permalink
Updated UnsavedChangesGuard to be a functional guard
Browse files Browse the repository at this point in the history
  • Loading branch information
swapnil-verma-gl committed Jun 26, 2024
1 parent bbe7698 commit 49b79b6
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 22 deletions.
1 change: 1 addition & 0 deletions lib/core/src/lib/auth/guard/auth-guard-sso-role.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,33 +15,27 @@
* 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';
import { tap } from 'rxjs/operators';

/**
* Guard responsible for protecting leaving page with unsaved changes.
*
* @returns boolean | Observable<boolean> flag indicating whether user has unsaved changes or not
*/
@Injectable({
providedIn: 'root'
})
export class UnsavedChangesGuard implements CanDeactivate<any> {
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<boolean> true when there is no unsaved changes or changes can be discarded, false otherwise.
*/
canDeactivate(): boolean | Observable<boolean> {
return this.unsaved ?
this.dialog.open<UnsavedChangesDialogComponent, undefined, boolean>(UnsavedChangesDialogComponent, {
maxWidth: 346
}).afterClosed().pipe(tap((confirmed) => this.unsaved = !confirmed)) : true;
}
}
export const UnsavedChangesGuard = (): boolean | Observable<boolean> => {
let unsaved = false;
const dialog = inject(MatDialog);
return unsaved
? dialog
.open<UnsavedChangesDialogComponent, undefined, boolean>(UnsavedChangesDialogComponent, {
maxWidth: 346
})
.afterClosed()
.pipe(tap((confirmed) => (unsaved = !confirmed)))
: true;
};

0 comments on commit 49b79b6

Please sign in to comment.