- 创建一个名为AuthService的服务,用于存储用户身份验证状态和用户信息。该服务应该有一个名为isAuthenticated的布尔值,以指示用户是否已登录,并有一个名为currentUser的属性,用于存储当前用户的信息。
@Injectable({
providedIn: 'root'
})
export class AuthService {
public isAuthenticated: boolean = false;
public currentUser: User;
constructor() { }
login(username: string, password: string) {
// perform login logic and set isAuthenticated and currentUser properties accordingly
}
logout() {
// perform logout logic and reset isAuthenticated and currentUser properties accordingly
}
}
- 在AppComponent中订阅AuthService的isAuthenticated属性,并根据其值更新侧边栏组件。
export class AppComponent implements OnInit {
public isAuthenticated: boolean = false;
constructor(private authService: AuthService) {}
ngOnInit() {
this.authService.isAuthenticated.subscribe((isAuthenticated: boolean) => {
this.isAuthenticated = isAuthenticated;
// call a method to update the sidebar component with the currentUser's information or reset it when the user logs out
});
}
}
- 在侧边栏组件中,订阅AuthService的currentUser属性,并根据其值更新用户信息。
export class SidebarComponent implements OnInit {
public currentUser: User;
constructor(private authService: AuthService) {}
ngOnInit() {
this.authService.currentUser.subscribe((currentUser: User) => {
this.currentUser = currentUser;
// update the sidebar with the currentUser's information
});
}
}