用例:我希望将已登录的用户重定向到/dashboard,将未登录的用户重定向到/landing。
第一个镜头:
{
path: '**',
redirectTo: '/dashboard',
canActivate: [AuthGuard],
},
{
path: '**',
redirectTo: '/landing'
}@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private auth: AuthService, private router: Router) {}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean|UrlTree> | Promise<boolean|UrlTree> | boolean | UrlTree {
return this.auth.isAuthenticated$
}
}所有用户都将重定向到仪表板页面。
第二次尝试:
{
path: '**',
redirectTo: '/home/loggedin',
canActivate: [AuthGuard],
data: { authGuard: { redirect: '/home/loggedout' } }
},
{
path: '**',
redirectTo: '/home/loggedin'
}@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private auth: AuthService, private router: Router) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean|UrlTree> | Promise<boolean|UrlTree> | boolean | UrlTree {
return this.auth.isAuthenticated$.pipe(
map(loggedIn => {
console.log(`A=${loggedIn} ${JSON.stringify(next.data.authGuard.redirect)}`)
if (!loggedIn && next.data.authGuard.redirect) {
return this.router.parseUrl(next.data.authGuard.redirect);
} else {
return false;
}
})
);
}
}似乎AuthGuard甚至都没有被调用。如果我使用一个组件而不是重定向?
{
path: '**',
component: RedirectingComponent,
canActivate: [AuthGuard],
data: { authGuard: { redirect: '/home/loggedout' }, redirectComponent: { redirect: '/home/loggedin' } }
}现在,这似乎是有效的,但它也是一个可怕的黑客。
如何才能使AuthGuards与重定向一起工作?
发布于 2020-03-15 18:03:44
你的AuthGuard可以强制导航。在您的第一次尝试中,将防护更改为如下内容:
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private auth: AuthService, private router: Router) {}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean|UrlTree> | Promise<boolean|UrlTree> | boolean | UrlTree {
// if user is authenticated just return true;
if (this.auth.isAuthenticated$) { return true; }
// if user is not authenticated redirect the user and return false
this.router.navigate(['/landing']);
return false;
}
}这应该会将未经验证的用户重定向到登录页。你也可以在angular docs here中查看这个例子。
发布于 2021-09-04 12:48:08
您可以使用children: []而不是设置component来实现这一点(如下所示)
{
path: '',
canActivate: [AuthGuard],
children: []
}https://stackoverflow.com/questions/60669468
复制相似问题