从BehaviourSubject检索的ngIf和Observable之间是否存在任何冲突?

时间:2019-06-17 04:24:02

标签: javascript angular typescript rxjs

我面临一个非常奇怪的问题。我在* ngIf中使用了Observable来显示错误以及异步管道。

问题在于,当Observable的值更新时,DOM也不会更新。仅当我单击页面或使用键盘获得焦点时,它才会更新。

那么,我应该如何将Observable与DOM绑定?

我尝试了各种方法来使用* ngIf,如果在* ngIf中使用if绑定DOM(带有或不带有异步管道等)来绑定DOM。

这就是我在HTML中使用的方式。

<div style="font-size: 0.9rem;" *ngIf="messageInfo | async"
     [ngClass]="{ 'alert': message, 'alert-success': message.type === 'success',
     'alert-danger': message.type === 'error' }">{{message.text}}
  <span (click)="close()" style="cursor: pointer; float: right;">
    <i class="material-icons icon-20 vertical-bottom">close</i>
  </span>
</div>

组件代码

export class AlertComponent implements OnInit {

  message: any;
  messageInfo: Observable<any>;

  constructor(private alertService: AlertService) {
  }

  ngOnInit() {
    this.messageInfo = this.alertService.getMessage();
    this.messageInfo.subscribe(message => {
      this.message = message;
    });
  }

  close() {
    this.alertService.close();
    this.message = undefined;
  }
}

服务

export class AlertService {

  private subject = new BehaviorSubject<any>(null);
  private keepAfterNavigationChange = false;

  constructor(private router: Router) {
    // clear alert message on route change
    router.events.subscribe(event => {
      if (event instanceof NavigationStart) {
        if (this.keepAfterNavigationChange) {
          // only keep for a single location change
          this.keepAfterNavigationChange = false;
        } else {
          // clear alert
          this.subject.next(null);
        }
      }
    });
  }

  success(message: string, keepAfterNavigationChange = false) {
    this.keepAfterNavigationChange = keepAfterNavigationChange;
    this.subject.next({type: 'success', text: message});
    // to hide message after 3 seconds.
    setTimeout(() => {
      this.close();
    }, 3000);
  }

  error(message: string, keepAfterNavigationChange = false) {
    this.keepAfterNavigationChange = keepAfterNavigationChange;
    this.subject.next({type: 'error', text: message});
    // to hide message after 3 seconds.
    setTimeout(() => {
      this.close();
    }, 3000);
  }

  getMessage(): Observable<any> {
    return this.subject.asObservable();
  }

  close() {
    this.subject.next(null);
  }
}

我以这种方式在所有其他组件中使用它:

<alert></alert>

我希望根据Observable的值更新UI,而无需单击或关注页面。不幸的是,只有当我使用鼠标或键盘专注于页面时,它才会更新。

2 个答案:

答案 0 :(得分:0)

按照以下建议更新ngZone内部的变量: 在您的情况下应该是这样的:

public constructor(private _ngZone: NgZone) {}
this.messageInfo.subscribe(message => {
   this._ngZone.run(() => {
      this.message = message;
   });
});

https://github.com/angular/angular/issues/7381#issuecomment-191456151

如果这不起作用,您可以尝试使用:

import { ChangeDetectorRef } from '@angular/core';
public constructor(private cdr: NgZone) {}
this.messageInfo.subscribe(message => {
      this.message = message;
      this.cdr.markForCheck();
});

答案 1 :(得分:0)

您可以尝试关注-

从组件中删除message变量 并删除this.messageInfo.subscribe行 然后像这样更新您的模板。

 <div style="font-size: 0.9rem;" *ngIf="(messageInfo | async) as message"
         [ngClass]="{ 'alert': message, 'alert-success': message.type === 'success',
         'alert-danger': message.type === 'error' }">{{message.text}}
      <span (click)="close()" style="cursor: pointer; float: right;">
        <i class="material-icons icon-20 vertical-bottom">close</i>
      </span>
    </div>