我有一个简单的 Angular 应用程序,它实现路由器防护来检查用户是否具有适当的访问权限。如果允许访问,警卫将返回
true
然后加载 DashboardComponent
。否则,它将重定向到ContactComponent
。
一切都很好,直到我在
ContactComponent
中按下浏览器刷新按钮。这样做后页面变成空白。我相信这是因为我没有在我的CanActivate
中放置ContactComponent
装饰。但如果我在 CanActivate
中放入 ContactComponent
,应用程序就会变得疯狂并无限加载。
如何在路由防护重定向用户的同一页面中处理刷新?
app-routing.module.ts
const routes: Routes = [
{ path: '', redirectTo: 'dashboard' }
{ path: 'contact', component: ContactComponent},
{ path: 'dashboard', CanActivate: [AccessGuard], component: DashboardComponent }
];
access.guard.ts
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.getAccess().pipe(map(access => {
if (access.valid) {
return true;
}
else {
this.router.navigate(['contact'], { state: { isValid: 'false' });
return false;
}
}
}
contact.component.ts
constructor(private router: Router) {
const extras = this.router.getCurrentNavigation().extras.state;
if (!extras.isValid) {
this.errorMessage = 'Access is not allowed. Please contact Administrator.';
}
}