【问题标题】:angular 4.4 *ngIf not updating when subscribed variable changesangular 4.4 *ngIf在订阅变量更改时不更新
【发布时间】: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


【解决方案1】:

为什么你有observer.complete();

删除该行并重新运行您的测试。一旦您拨打了complete(),您的next() 呼叫将被默默地忽略。有关详细说明,请参阅此post

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

【讨论】:

  • 我评论了observer.complete();,我又试了一次,但是当变量发生变化时,前面仍然没有变化。
猜你喜欢
  • 1970-01-01
  • 2018-05-08
  • 1970-01-01
  • 2019-06-05
  • 1970-01-01
  • 1970-01-01
  • 2018-01-24
  • 1970-01-01
  • 2021-03-18
相关资源
最近更新 更多