【发布时间】:2018-08-03 16:34:31
【问题描述】:
我的应用路由器文件定义了以下内容
export const router: Routes = [
{
path: '',
redirectTo: '/home',
pathMatch: 'full'
},
{
path: 'home',
canActivate: [AuthGuard],
component: LandingPageComponent
},
{
path: 'login',
component: LoginComponent
},
{
path: 'register',
component: RegisterComponent
},
{
path: '404',
component: PageNotFoundComponent
},
{
path: '**',
component: PageNotFoundComponent
}]
当我尝试导航到 URL http://localhost:4200/home 时,AuthGuard 启动并且页面被重定向到 http://localhost:4200/login 页面。
但是当我使用 url http://localhost:4200 redirectTo 导航时,它会直接打开 http://localhost:4200/home 页面而不是 http://localhost:4200/login 页面。
它应该调用AuthGuard 并重定向到loginPage,对吧?
关于以下修改后的路由定义,尝试导航到http://localhost:4200 应该重定向到http://localhost:4200/login,但它又打开了http://localhost:4200/home
{
path: '',
canActivate: [AuthGuard],
component: LandingPageComponent
}
这是 Angular 6 的错误吗?感谢任何帮助/指针。
我的auth.guard.ts文件如下
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (localStorage.getItem('currentUser')) {
// logged in so return true
return true;
}
// not logged in so redirect to login page with the return url
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
return false;
}
}
【问题讨论】:
-
你能告诉我们你的 auth-guard 吗?
-
我已经添加了