繁体   English   中英

canActivate无法在Angular中使用重定向的路由

[英]canActivate not working with redirected routes in Angular

我的应用路由器文件定义了以下内容

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/homeAuthGuard启动,页面重定向到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;
  }
 }

尝试删除斜杠:

{
    path: '',
    redirectTo: 'home',    //<- No slash here
    pathMatch: 'full'
},

如果那没有帮助,请尝试启用路由跟踪,以查看是否提供了有关保护措施未执行原因的任何信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM