当我的 auth-guard 被调用时,在使用 canActivate 的路由上重新加载页面时,它会短暂呈现登录页面 - Angular v17

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

问题基本上是,当我登录到仪表板时,每次重新加载浏览器页面时,它都会立即呈现登录组件

令牌服务

export class TokenService {
  isAuthentications: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
  constructor(@Inject(PLATFORM_ID) private platformId: Object) { 
    const token = this.getToken();
    if(token){
      this.updateToken(true)
    }
  }

  setToken(token: string){
    this.updateToken(true);
    localStorage.setItem('user', token)
  }
  updateToken(status: boolean){
    this.isAuthentications.next(status)
  }
  getToken(): string | null{
    if (typeof window !== 'undefined' && window.sessionStorage) {
      return localStorage.getItem('user');
    }

    return null
  }
}

AuthGuard

export const authGuard: CanActivateFn = (route, state) =\> {
const tokenService = inject(TokenService)
const router = inject(Router)
// tokenService.isAuthentications.subscribe({
//   next: (v) =\> {
//     if(!v){
//         router.navigate(\['/login'\])
//     }
//   }
// })
// return true;

return tokenService.isAuthentications.pipe(map( (user) =\> {
if(!user){
return router.createUrlTree(\['/login'\]);
}else{
return true
}
}))
};
Routes
export const routes: Routes = [
  { path: 'login', component: LoginComponent },
  { path: '', redirectTo: 'login', pathMatch: 'full'},
  {path: '' , component: LayoutComponent, children: [
    {path: 'dashboard', component: DashboardComponent, canActivate: [authGuard]  }
  ]}
];

显示问题的gif

我已经尝试过其他方法来保护路线,但是,每当我的守卫应该重定向到“登录”时,它就会出现这种行为

angular authentication routes angular17 auth-guard
1个回答
0
投票

您可以尝试使用

APP_INITIALIZER
以便在应用程序加载之前初始化令牌,这可能会解决您的问题!

这将使令牌在 authFn 初始化之前设置,因此它将具有正确的值,并且希望不会显示登录屏幕!

function initializeApp(tokenService: TokenService): void {
    const token = this.getToken();
    if(token){
       this.updateToken(true)
    }
}
 

@NgModule({
 imports: [BrowserModule],
 declarations: [AppComponent],
 bootstrap: [AppComponent],
 providers: [{
   provide: APP_INITIALIZER,
   useFactory: () => initializeApp,
   deps: [TokenService],
   multi: true
  }]
 })
export class AppModule {}

独立 APP_INITIALIZER 示例

© www.soinside.com 2019 - 2024. All rights reserved.