angular - angular 4.4 *ngIf在订阅变量更改时不更新
问题描述
如果分配了变量,我想让网络的一些元素出现或消失。我订阅了一项服务来获取此变量,但带有 *ngIf 的元素在变量更改时不会更新。
users.service 中的服务是:
public getMyProfile(): Observable<Profile> {
return Observable.create(observer => {
this.getProfile().subscribe(
profile => {
this.avatarService.getAvatar(profile.avatarId).subscribe(
avatar => {
profile.avatar = avatar;
observer.next(profile);
observer.complete();
}, error => observer.error(error));
}, error => observer.error(error));
});
}
该组件具有获取配置文件变量的订阅:
export class NavBarComponent implements OnInit {
public profile: Profile;
private subscription: Subscription;
constructor(
public alertService: AlertService,
public utilsService: UtilsService,
public userService: UserService
) {
this.utilsService.currentUser = Login.toObject(localStorage.getItem(AppConfig.LS_USER));
this.utilsService.role = Number(localStorage.getItem(AppConfig.LS_ROLE));
}
ngOnInit(): void {
this.userService.getMyProfile().subscribe(
((profile: Profile) => {
this.profile = profile; // this is the subscription where I get the profile variable
}),
((error: Response) => {
this.alertService.show(error.toString());
}));
}
}
在模板中,如果有配置文件,我有一个 *ngIf 来显示或隐藏元素:
<a *ngIf="profile" mat-button routerLink="/home">{{ 'HOME.TITLE' | translate }}</a>
我一直在寻找和尝试不同的东西,但元素总是可见或总是不可见。当配置文件变量更改时,它们不会更改。但是,如果变量配置文件发生更改并且我重新加载,那么它会根据需要更改。
解决方案
你为什么有 observer.complete();
?
删除该行并重新运行测试。一旦你打电话complete()
,你的next()
电话将被默默地忽略。有关详细说明,请参阅此帖子。
一个普通的主题(使用 new Rx.Subject() 创建)实现了该语法:当 onCompleted 被调用一次时,所有后续对 onNext 的调用都将被忽略。对同一观察者的第二次 onCompleted 调用也会被忽略。如果观察者订阅了主题的可观察端,它的 onComplete 回调将立即被调用
推荐阅读
- reactjs - 改变 setState 中的状态还是克隆它更好?
- node.js - 我可以阻止 ejs 评估带有连字符的日期吗?
- shell - gnuplot 错误:无法打开脚本文件“用点绘制 Deaths.txt”
- c# - 子对象变换位置,旋转,比例远离原点不正确?
- python - 如何使用 tkinter 阻止画布上的所有内容向上移动
- python - 如何根据某些特定关键字提取/过滤 csv 文件的行?
- c++ - 类中的OpenGL函数
- javascript - 查找 DOM 元素的所有侦听器
- java - 你能帮我打印一个用二叉搜索树制作的家谱吗?
- javascript - 用于忽略子字符串搜索中的特殊字符的正则表达式