我实现了angular的登录。 它运作良好,但我想在成功通过身份验证后进行重定向。
从服务器接收用户后,重定向不起作用。 如果我刷新页面并使用登录名,它将起作用。
我从Web服务接收到一个对象,并将其保存到“ localStorage”。 我使用BehaviourSubject观察我的当前用户。
如果我按“登录”,则会遇到身份验证防护,但身份验证防护不认识该用户。 (它为空)
我怎么了?
Auth.guard.ts
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
constructor(
private router: Router,
private authenticationService: AuthService
) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
console.log(this.authenticationService.currentUserValue);
if (this.authenticationService.currentUserValue) {
return true;
}
// not logged in so redirect to login page with the return url
this.router.navigate(['/entrance/login'], { queryParams: { returnUrl: state.url } });
return false;
}
}
@Injectable({
providedIn: 'root'
})
export class AuthService {
private currentUserSubject: BehaviorSubject<User>;
constructor(private http: HttpClient) {
this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
}
public get currentUserValue(): User {
return this.currentUserSubject.value;
}
login(username: string, password: string) {
return this.http.post<User>('/api/auth', { username, password }).pipe(map(user => {
// login successful if there's a jwt token in the response
if (user && user.token) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
this.currentUserSubject.next(user);
}
return user;
}));
}
this.authService.login(email, password).pipe(first()).subscribe(data => {
this.router.navigate([this.returnUrl]);
});
我想在登录后直接重定向而不刷新。
您看到任何错误吗?