0

我正在尝试找到一个解决方案,该解决方案将在首先加载角度(html和组件)之前重定向到授权端点。这甚至可能吗?或者是否可以在我的主要 app.component 上使用 CanActivate auth guard?

我正在使用身份验证保护,就像任何其他角度项目一样。但它在重定向到授权端点之前首先加载 html。

这是我到目前为止所做的:

(我的路由组件)

const routes: Routes = [
{
    path: '',
    redirectTo: 'main',
    pathMatch: 'full',
    canActivate: [AdminRouteGuard]
},
{
    path: 'main',
    component: MainComponent,
    canActivate: [AdminRouteGuard]
},
{
    path: '**',
    redirectTo: 'main',
    pathMatch: 'full',
    canActivate: [AdminRouteGuard]
}];

(我的路线守卫)

 export class AdminRouteGuard implements CanActivate {
  constructor(@Inject(DOCUMENT) private document: any, private _authService: AuthService, private router: Router) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

    if (this._authService.isLoggedIn()) {
      return true;
    }
    
    else {
      return this._authService.login();
    }}}
4

1 回答 1

0

有可能,您应该为此使用 APP_INITIALIZER 提供程序。然后为了使其更健壮,将其与 Auth Guards 结合使用。由于您没有说明您正在使用什么身份管理解决方案,因此我提供了一种通用方法来创建您自己的初始化程序。

function authInit(authService: AuthService) {
  return () => {
    // Do the authentication here and return Promise
    // Code here depends on your service and/or on your IM solution
  })
}

@NgModule({
  declarations: [AppComponent],
  imports: [AppRoutingModule, BrowserModule],
  providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: authInit,
      multi: true,
      deps: [AuthService],
    },
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}

您自己的工厂函数authInit返回函数,如果该函数返回 Promise,则在 Promise 解决之前初始化不会完成。这应该可以解决问题。

于 2020-12-22T06:41:52.180 回答