登录 router.navigate 后进入守卫状态,但在守卫状态下它不会获得更新的值。
我的
app.config.ts
是:
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
provideHttpClient(withInterceptorsFromDi()),
{
provide: APP_INITIALIZER,
useFactory: (sessionService: SessionManagementService, authService: AuthService) => {
return () => sessionService.init()
},
deps: [SessionManagementService, AuthService],
multi: true
},
{
provide: HTTP_INTERCEPTORS,
useClass: DefaultInterceptor,
multi: true
}
]
};
app.routes.ts
是:
export const routes: Routes = [
{
canActivate: [AuthGuard],
path: '',
loadChildren: () => import('./layout/main/main.routes').then(m => m.mainRoutes)
},
{
canActivate: [LoginGuard],
path: 'auth',
loadChildren: () => import('./auth/auth.routes').then(m => m.authRoutes)
},
{
path: '**',
redirectTo: ''
}
];
login.component.ts 是:
@Component({
selector: 'agro-login',
standalone: true,
imports: [
FormsModule,
PasswordModule,
NgIf,
InputTextModule,
ButtonModule,
RippleModule
],
providers: [SessionManagementService, MessageService],
templateUrl: './login.component.html',
styleUrl: './login.component.scss'
})
export class LoginComponent extends BaseComponent {
@ViewChild('orgForm') orgForm: NgForm;
userCredential: UserCredential = new UserCredential();
phoneRegex: RegExp = MOBILE_NUM_REGEX;
constructor(private messageService: MessageService,
private authService: AuthService,
private router: Router,
private sessionManagementService: SessionManagementService) {
super();
}
login() {
this.enableBusyState();
this.authService.login(this.userCredential).subscribe({
next: async response => {
await this.sessionManagementService.refreshSession();
await this.router.navigate(['']);
},
error: error=>{
this.disableBusyState();
this.messageService.add({severity:'error', summary: 'Error', detail: 'Incorrect username/password'});
}
})
}
}
}
刷新会话会更新 sessionInfo 值。但是当我导航到 authGuard 中的仪表板时,没有更新的 sessionInfo 值。我的授权卫士是:
export class AuthGuard {
constructor(private router: Router,
private sessionManagementService: SessionManagementService) {
}
canActivate(): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.checkAccess();
}
checkAccess() {
if (this.sessionManagementService.sessionInfo.isAuthenticated) {
if (this.sessionManagementService.sessionInfo.userAuthInfo.type === 'ADMIN') {
return true;
}
}
this.router.navigate(['auth/login']);
return false;
}
}
我想知道为什么保护值没有更新?以及如何更改配置以使其正常工作
终于找到问题了。我在
sessionMangementService
login.component.ts
中添加了providers: [sessionMangementService]
。这将创建新实例并覆盖旧实例。
我将这个
sessionMangementService
放入 app.config.ts
提供者数组中,并从登录组件中删除。然后就可以了。