是的,我知道这是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;
})
);
}
但是问题是,单击浏览器的back button
时,防护只会执行一次,因此clicking again
用户实际上可以离开。
还按角度检查了问题:https://github.com/angular/angular/issues/12851
但它尝试通过在返回false之前再次导航到当前路线来解决该问题,如下所示:
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;
})
);
}
这时警报被调用了两次,因为在返回false之前,我导航到currentState,因此可以再次取消角度运行,但是在再次单击后退按钮后,不会调用canDeactivate。 路由表:
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}}
];
出什么问题了?预先感谢。