我的Angular应用程序目前有这些routes
。
const routes: Routes = [
{ path: '', component: DashboardComponent },
{ path: 'login', component: LoginComponent },
{ path: 'upload', component: UploadPictureComponent, canActivate: [AngularFireAuthGuard] },
{ path: 'view', component: ListPictureComponent, canActivate: [AngularFireAuthGuard] },
{ path: '**', component: NotFoundComponent },
];
当前行为:如果用户未登录并转到路由upload
或view
,则他们的路由将被阻止,看不到任何内容。
期望行为:如果用户转到任何被阻止的路线,我想向他们显示NotFoundComponent
。
我无法解决的问题是,当路由被警卫拒绝时,Angular会取消路由事件。
我给出这个答案是可能的解决方案之一,我不知道这是最好的还是最好的做法。
-
我会保留一个常量字符串,用于所有手动回退路径导航。也许是这样的:const FALLBACK_PATH="未找到"。我会把它放在一个共享的位置,我可以在任何我想要的组件中使用。
-
在
AngularFireAuthGuard
防护中,当登录条件失败时,我会执行以下操作:this.router.navigateByUrl(FALLBACK_PATH, { skipLocationChange: true }); return false;
注意:我正在做
skipLocationChange
,因为我不希望错误的路径显示在URL中,你可以拥有它,也可以不拥有它,这取决于你的要求。此外,上面的代码没有经过测试,只是为您提供了一种方法。
canActivate
当前可以返回所需的URLTree。您可以在AngularFireAuthGuard
:中测试登录用户的重定向
constructor(private _authService: AuthService, private _router: Router){}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | boolean | UrlTree
{
if(this._authService.isLoggedIn) {
// runs your current authorization logic
} else {
// the argument of parse is any string that doesn't represent
// a real route
return this._router.parse('go-to-page-not-found');
}
}
如果canActivate
返回错误,则必须手动重定向到"NotFoundComponent">
canActivate(): boolean {
if (!this.auth.isAuthenticated()) {
this.router.navigate(['login']);
return false;
}
return true;
}