I have a CanDeactivateGuard set up for my routes, and I am looking to pass data to it. The guard is designed to prompt users to save any unsaved changes before navigating away. The data that needs to be passed into the dialog comes from a Subscription.
I came across this helpful answer while trying to find a solution: How to pass parameters to constructor of canActivate?
However, it seems a bit too simplified for my specific scenario because I need to pass a Subscription along with my routes, which poses a challenge.
This is the current implementation of my guard:
export class PendingChangesGuard
implements CanDeactivate<ComponentCanDeactivate> {
constructor(
private myDialogService: MyDialogService,
) {}
canDeactivate(
component: ComponentCanDeactivate,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState?: RouterStateSnapshot
): boolean | Observable<boolean> {
return component.canDeactivate() || this.openConfirmDialog();
}
openConfirmDialog() {
const ref = this.myDialogService.open(MyDialogComponent, /** Pass a CONFIG object here **/);
return ref.afterClosed$();
}
}
In the modalDialogService.open()
method, the goal is to pass data as the second argument.
For fetching the necessary content in another component using different data from the same service call, I have implemented it like so:
export class MyComponent implements OnInit, OnDestroy {
myContent: any;
myContentSubscription: Subscription;
constructor(private myContentService: MyContentService) {}
ngOnInit() {
this.myContentSubscription =
this.myContentService.myContent$.subscribe(
flag => {
if (flag) {
this.myContent = this.myContentService.getMyContent();
}
}
);
}
}
The myContentSubscription
will populate the necessary data required for opening the modal. However, I believe that the Guard should not handle the service call. Additionally, due to the asynchronous nature of the call, there needs to be a way to wait before passing the data into the modal.
Where would be the appropriate place to place the subscription code so that the Guard can access it when invoked?