2

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.

Nix
  • 57,072
  • 29
  • 149
  • 198
Alex
  • 1,230
  • 2
  • 24
  • 46

1 Answers1

1

Why do you have observer.complete();?

Remove that line and re-run your test. Once you have called complete(), your next() calls will silently be ignored. See this post for a detailed explanation.

a vanilla subject (created with new Rx.Subject()) implements that grammar : when onCompleted has been called once, all subsequent calls to onNext are ignored. Second call of onCompleted on the same observer is also ignored. If an observer subscribes to the observable side of the subject, its onComplete callback will immediately be called

Nix
  • 57,072
  • 29
  • 149
  • 198
  • I commented the `observer.complete();` and I tried again, but still no changes in the front when the variable changes. – Alex Nov 25 '18 at 23:18