角度4.4 * ng如果订阅变量更改时不更新

时间:2018-11-25 22:25:53

标签: angular subscription angular2-observables 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>

我一直在搜索并尝试不同的东西,但是元素始终可见或始终不可见。当配置文件变量更改时,它们不会更改。但是,如果变量配置文件发生变化并且我重新加载,则它会根据需要进行更改。

1 个答案:

答案 0 :(得分:1)

您为什么有observer.complete();

删除该行,然后重新运行测试。致电complete()后,您的next()呼叫将被忽略。有关详细说明,请参见此post

  

香草主题(使用新的Rx.Subject()创建)实现该语法:当一次调用onCompleted时,将忽略对onNext的所有后续调用。在同一观察者上对onCompleted的第二次调用也将被忽略。如果观察者订阅了该主题的可观察端,则其onComplete回调将立即被调用

相关问题