首先,我们需要确保在AuthGuard中实现的CanActivate方法返回一个Observable
因此,我们可以将CanActivate方法返回一个Promise
canActivate(): Promise {
return new Promise((resolve) => {
this.authService.isAuthenticated().subscribe((authenticated) => {
if (authenticated) {
resolve(true);
} else {
this.router.navigate(['/login']);
resolve(false);
}
});
});
}
其次,我们需要确保每次导航到受保护的页面时都调用AuthService,并且在Auth Service中应该使用BehaviorSubject来跟踪用户的身份验证状态,以便在每次订阅时都能获取最新状态,如下所示:
export class AuthService {
private isAuthenticatedSubject = new BehaviorSubject(
this.token != null
);
get isAuthenticated(): Observable {
return this.isAuthenticatedSubject.asObservable();
}
login(username: string, password: string): Observable {
// call login api and set token to localStorage
this.isAuthenticatedSubject.next(true);
// return response
}
logout(): void {
// remove token from localStorage
this.isAuthenticatedSubject.next(false);
}
}
最后,在AppComponent中,我们需要订阅AuthService的isAuthenticated流,并将其绑定到一个本地属性中,以便在模板中获取用户的身份验证状态。
export class AppComponent {
isAuthenticated: boolean;
constructor(private authService: AuthService) {
this.authService.isAuthenticated.subscribe(
(authenticated) => (this.isAuthenticated = authenticated)
);
}
}
使用这个解决方法,AuthGuard和AuthService应该能够按预期工作,并始终保持同步。