如何在 Angular Guard 中使用/返回承诺?

问题描述 投票:0回答:0

我正在尝试在 Angular 中实现一个 Guard,它将检查用户是否经过身份验证并相应地重定向他但是当我实现它时,我得到了这个错误

Error: Uncaught (in promise): TypeError: Class constructor NotSignedInGuard cannot be invoked without 'new'

我的守卫是

async
并返回
Promise<boolean>
,这是我如何实现的

@Inject({
  providedIn: 'root'
})
export class NotAuthenticatedGuard implements CanActivate {

  constructor(private authService: AuthService, private router: Router) {
  }

  async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
    const isAuthenticated = await this.authService.isAuthenticated();

    if (isAuthenticated) {
      return true
    } else {
      this.router.navigate(['/auth/sign-in'])
      return false
    }

  }

}

这就是我将它集成到

AppRoutingModule

中的方式
const routes: Routes = [
  {
    path: 'posts',
    loadChildren: () => import('./posts/posts.module').then(m => m.PostsModule),
    canActivate: [NotAuthenticatedGuard],
  },
];

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

你能告诉我哪里出了问题吗?以及如何解决?谢谢

angular typescript angular-routing angular-router angular-guards
© www.soinside.com 2019 - 2024. All rights reserved.