首页 > 解决方案 > 重新加载页面将我带到角度 cli 中的根路径

问题描述

我是 Angular 的新手。我已经为我的应用程序配置了路由。但是每当刷新页面时,即使当前路由不是root or default路由,应用程序也会将我重定向到root. 这就是我配置路线的方式。

const routes: Routes = [
  { path: '', loadChildren: './auth/auth.module#AuthModule'  },
  { path: 'donors', component: DonorComponent, canActivate: [AuthGuard], children: [
    { path: 'seeDonors', component: SeeDonorComponent, pathMatch: 'full' },
    { path: 'newDonor', component: NewDonorComponent }
  ] },
  { path: 'bloodStock', component: BloodStockComponent },
  { path: 'donationCenter', component: DonationCenterComponent, canActivate: [AuthGuard] },
  { path: 'branch', component: BranchComponent, canActivate: [AuthGuard] }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: [AuthGuard]
})
export class AppRoutingModule { }

并且 AuthGuard 检查用户是否已登录这里是代码

export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): boolean | Observable<boolean> | Promise<boolean> {
    const isAuth = this.authService.getIsAuth();
    if (!isAuth) {
      // this.router.navigate(['/']);
    } else {
    }
    return isAuth;
  }
}

帮我解决这个问题...如果我的问题不清楚,我会更详细地解释。感谢您的时间!

标签: angular

解决方案


请检查守卫的逻辑。我想也许问题出在他们的

我这里有一个例子

    async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
            const user = await this.myservice.getUserAuthState();
            if (!user) {
                return false;
            }

            return true;
        }

您将需要返回 true 或 false,而不是在警卫中重定向用户。只有你有权访问该组件或模块的警卫,如果你没有,警卫会将你重定向到主 url

希望它会有所帮助。


推荐阅读