我有下一个 Angular Guard:
export class AdminGuard implements CanActivate {
constructor(
private readonly router: Router,
private readonly userService: UserService
) { }
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.userService.getUserRoles().pipe(
map(roles => {
if (roles.admin) {
return true
}
this.router.navigate(['/'])
return false
})
)
}
}
这是来自服务的方法,它返回 Observable:
public getUserRoles(): Observable<any> {
return this.store.pipe(
select('user'),
map(({ roles }) => roles)
)
}
这在我在页面之间导航时有效,但是当我直接在 URL 中输入某些路由时,例如“myapp.com/admin”,它会自动返回 false,并且防护不起作用。如何让它正常工作?