【发布时间】:2019-04-27 14:21:02
【问题描述】:
如果分配了变量,我想让网络的某些元素出现或消失。我订阅了一个服务来获取这个变量,但是当变量改变时,带有 *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>
我一直在寻找和尝试不同的东西,但这些元素总是可见或不可见。当配置文件变量更改时,它们不会更改。但是,如果变量配置文件发生更改并且我重新加载,那么它会根据需要更改。
【问题讨论】:
-
如果在 NavBarComponent 上将配置文件属性设置为 null 怎么办?
标签: angular subscription angular2-observables angular-ng-if