Angular 角度:路由重定向问题
我正在使用angular中的路由器重定向用户,具体取决于用户是否登录及其当前URL: 下面是我的应用程序路由模块中的路由:Angular 角度:路由重定向问题,angular,typescript,web-frontend,Angular,Typescript,Web Frontend,我正在使用angular中的路由器重定向用户,具体取决于用户是否登录及其当前URL: 下面是我的应用程序路由模块中的路由: const routes: Routes = [ { path: 'home', component: HomeComponent, canActivate: [RouteGuardService] }, { path: 'login', component: LoginComponent}, { path: '', redirectTo: 'login', p
const routes: Routes = [
{ path: 'home', component: HomeComponent, canActivate: [RouteGuardService] },
{ path: 'login', component: LoginComponent},
{ path: '', redirectTo: 'login', pathMatch: 'full'}, // redirects to '' exists hence keep this in mind when redirecting
{ path: '**', redirectTo: 'home' },
];
在用户未登录但试图访问“/home”目录的情况下,他/她被重定向到“/login”。我用来实现这一点的代码是
if (accessGranted){
return true;
} else {
// tell router to navigate to login pag
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
return false;
}
这段代码基本上可以工作,但有一个错误仍然存在:如果我试图在未登录的情况下访问主页,我首先会被重定向到“/”,只有当我刷新时,我才会被重定向到登录。我真的不明白为什么会发生这种情况,我很想解决这个问题
致以最良好的祝愿,
萨姆
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (!this.authService.isLoggedIn) {
return this.router.parseUrl(`/login?returnUrl=${state.url}`);
} else {
return true;
}
}
}