首页 > 解决方案 > 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>

我一直在寻找和尝试不同的东西,但元素总是可见或总是不可见。当配置文件变量更改时,它们不会更改。但是,如果变量配置文件发生更改并且我重新加载,那么它会根据需要更改。

标签: angularsubscriptionangular2-observablesangular-ng-if

解决方案


你为什么有 observer.complete();

删除该行并重新运行测试。一旦你打电话complete(),你的next()电话将被默默地忽略。有关详细说明,请参阅此帖子

一个普通的主题(使用 new Rx.Subject() 创建)实现了该语法:当 onCompleted 被调用一次时,所有后续对 onNext 的调用都将被忽略。对同一观察者的第二次 onCompleted 调用也会被忽略。如果观察者订阅了主题的可观察端,它的 onComplete 回调将立即被调用


推荐阅读