【问题标题】:canActivate not working with redirected routes in AngularcanActivate 不适用于 Angular 中的重定向路由
【发布时间】: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 吗?
  • 我已经添加了

标签: angular routing angular6


【解决方案1】:

尝试删除斜线:​​

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

如果这没有帮助,请尝试打开路由跟踪,看看是否可以提供任何有关守卫未执行原因的信息。

【讨论】:

  • 不走运。尝试跟踪,日志似乎不友好,对我来说没有多大意义。但是我注意到,当警卫调用失败时Router Event: GuardsCheckEnd 具有属性shouldActivate: true,否则为false。顺便说一句,这是 Pluralsight 中的一个很棒的教程。谢谢你
猜你喜欢
  • 1970-01-01
  • 2017-04-12
  • 2021-02-15
  • 2019-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-03
相关资源
最近更新 更多