I want to make some elements of the web appear or dissapear if there is a variable assigned or not. I subscribe to a service to obtain this variable, but the elements with the *ngIf do not update when the variable changes.
The service in users.service is:
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));
});
}
the component has the subscription to get the profile variable:
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());
}));
}
}
And in the template I have an *ngIf to show or hide the elements if there is a profile or not:
<a *ngIf="profile" mat-button routerLink="/home">{{ 'HOME.TITLE' | translate }}</a>
I've been searching and trying different things, but the elements are always visible or always invisible. They don't change when profile variable changes. But if variable profile changes and I reload then it changes as desired.