登录后,我可以在控制台上看到当前的用户值,但是我没有重定向到使用authguard服务的主页;仅当刷新页面并再次输入凭据时...如果重定向到没有保护措施的页面,或者如果失去主页保护措施,则首次登录成功。另外,在导航栏中,注销后,当前用户的名称不会消失,只有当我刷新它时...某人可以帮助我了解此行为并解决问题吗?
AuthService
private currentUserSubject: BehaviorSubject<User>;
public currentUser: Observable<User>;
constructor(private http: HttpClient, private router: Router) {
this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
this.currentUser = this.currentUserSubject.asObservable();
}
public get currentUserValue(): User {
return this.currentUserSubject.value;
}
login(credentials: any) {
return this.http.post('/users/authenticate', credentials)
.pipe(map(user => {
if (user)
localStorage.setItem('currentUser', JSON.stringify(user));
return user;
}))
}
logout() {
localStorage.removeItem('currentUser');
this.currentUserSubject.next(null);
this.router.navigate(['/login'])
}
登录名:
onSubmit() {
if (this.loginForm.invalid)
return;
let credentials = {
userName: this.userName.value,
password: this.password.value
}
this.authService.login(credentials).subscribe(data => {
let returnUrl = this.route.snapshot.queryParamMap.get('returnUrl');
this.router.navigate(['/home'||returnUrl ]);
console.log(data);
},(error:any)=>{
console.log(error)
this.errorMessage=true;
})
}
此模块路由:
export const routes: Routes = [
{path:'home', component: HomeComponent , canActivate:[AuthGuardService] },
{path:'movieDetail/:title', component:DetailComponent},
{path: 'signup', component: SignupComponent},
{path: 'login', component: LoginComponent},
{path:'', redirectTo:'login', pathMatch:'full'}
];
后卫:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (this.authService.currentUserValue) {
return true;
} else {
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
return false;
}
}
注意,我使用了一个falsebackend,它返回了一个伪造的jwt令牌,但是我认为它与任何事情都没有关系...
答案 0 :(得分:1)
我认为登录后没有发出BehaviorSubject currentUserSubject
。
请检查路线为this.authService.currentUserValue
时返回的/home
。
如果其为null
或undefined
,请进行设置。同样,当您重新加载时,它不会清除本地存储,因此您服务的构造函数会设置BehaviorSubject。
我建议您修改auth.guard.ts
。
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (localStorage.getItem('currentUser')) {
return true;
} else {
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
return false;
}
}