angular - 从 BehaviorSubject 获取用户名并在 Angular 11 中登录后在标题部分显示用户名需要刷新
问题描述
我正在创建一个角度应用程序。我有 AuthenticationService 类。登录后,我将帐户对象放入 BehaviorSubject 可观察对象中。这样我就可以订阅 observable 并获取 Account 对象的必要信息。这是我的代码:
private accountSubject: BehaviorSubject<AccountInfo>;
public account: Observable<AccountInfo>;
constructor(
private router: Router,
private service: ApplicationService) {
// behaviour subject
this.accountSubject = new BehaviorSubject<AccountInfo>(JSON.parse(localStorage.getItem('account')));
this.account = this.accountSubject.asObservable();
}
public get accountValue(): AccountInfo {
return this.accountSubject.value;
}
login(username: string, password: string) {
return this.service.post<any>(`${this.apiPATH}login`, { username, password })
.pipe(map(user => {
localStorage.setItem('account', JSON.stringify(user.account));
this.accountSubject.next(user);
return user;
}));
}
现在登录后我想在我的标题部分显示用户名。因此,在标头组件中,我订阅了观察者并尝试通过字符串插值显示用户名。这是我的标题组件代码:
account: AccountInfo;
username: string;
userPhotoUrl: string;
constructor(private authService: AuthenticationService) {
this.authService.account.subscribe(x => this.account = x);
}
logout() {
this.authService.logout();
}
ngOnInit() {
this.username = this.account.name;
}
看法
<h5 class="mb-0 text-white nav-user-name">{{username}}</h5>
为什么会发生这种情况我不知道。谁能帮我理解这个问题并得到解决方案。我也不想将信息放在本地存储或会话中。
我也尝试过这种方式。相反,在构造函数中订阅 observable,我将代码放在 ngInit 中,如下面的代码。但它也不起作用。
ngOnInit() {
this.authService.account.subscribe(x => {
this.account = x;
this.username = x.name;
});
}
解决方案
这可能只是一个时间问题,可能ngOnInit
是在设置之前被调用account
,或者没有触发更改检测。尝试对构造函数中的订阅进行以下更新
constructor(private cd: ChangeDetectorRef) {
this.authService.account.subscribe(x => {
this.account = x
this.userName = this.account.name;
// log the result to be sure it's actually being received
console.log('account: ', x)
// in case it's not detecting changes
this.cd.detectChanges()
})
}
推荐阅读
- laravel - 验证数组并在彼此之间传递字段值
- java - 在 Spring Boot 中启用 ssl 的最佳做法是什么?
- python - DreamScrape 错误:TypeError:不能在类似字节的对象上使用字符串模式
- c# - DocuSign 签名不会取代 usign Rest API PDF 表单字段
- django - Django 模型设计 - ManyToManyField 或 ForeignKey:选择选项
- python - 即使什么都没有,我的脚本也会继续打印
- python - 在python中的特定字符之前删除空格?
- python - 如何使用列表理解获得给定列表的所有元素的总和?
- android - 如何使用 minSDK = 21 在 Android/Kotlin 上处理日期?
- docker - Docker 用 yarn monorepo 撰写文件