Can Deactivate guard runs only once in Angular


Can Deactivate guard runs only once in Angular



Yes I know it is a duplicate issue but previous post does not solve it.
Guard code:


duplicate issue


canDeactivate(component: ExamEndedComponent,
currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.store.select(fromRoot.getExamStatus)
.pipe(
take(1),
map((res: string) => {
console.log(res);
if (res === 'started') {
alert('stop');
console.log(currentState.url);
return false;
}
return true;
})
);
}



but the problem is when clicking on back button of browser the guard executes only once so when clicking again user can actually navigate away .
Also checked the issue in angular : https://github.com/angular/angular/issues/12851
but it tries to solve the issue by navigating again to the current route before return false like below :


back button


clicking again


canDeactivate(component: ExamEndedComponent,
currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.store.select(fromRoot.getExamStatus)
.pipe(
take(1),
map((res: string) => {
console.log(res);
if (res === 'started') {
alert('Deactivation blocked');
console.log(currentState.url);
this.router.navigate([currentState.url]);
return false;
}
return true;
})
);
}



At this point alert is called twice because before returning false I navigate to currentState so angular runs candeactivate again but after clicking again at back button the canDeactivate is not called.
Routing table :


const appRoutes: Routes = [
{ path: 'Authentication', component: AuthComponent},
{path: '', redirectTo: 'home', pathMatch: 'full'},
{ path: 'home', component: HomeComponent, children: [
{path: '', redirectTo: 'exam', pathMatch: 'full'},
{path: 'exam', component: ExamComponent, children: [
{path: '', redirectTo: 'start', pathMatch: 'full'},
{path: 'start', component: ExamStartComponent},
{path: 'started', component: ExamQuestionsComponent,
canActivate: [ExamQuestionsGuard],
canDeactivate: [ExamStartedDeactivateGuard]},
{path: 'ended', component: ExamEndedComponent, canDeactivate: [ExamStartedDeactivateGuard]}
], resolve: {exam: ExamResolver}}
],
canActivate: [AuthGuard], resolve: {sign: SignInResolver}}
];



What is the problem ? Thanks in advance .









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

how to run turtle graphics in Colaboratory

Export result set on Dbeaver to CSV