首页 > 解决方案 > Angular BehaviorSubject - 如何删除所有数据?

问题描述

我不是传统的 UI 开发人员,而且我还没有完全理解BehaviorSubject. 我们有一个 ErrorNotificationService。当页面上发生错误时,我们将错误推送到addError. 当错误被解除时,我们将其从removeErrorById, 或中删除removeErrorByIdentity

我将错误推送到 BehaviorSubject,当我从页面导航时,我想删除它持有的所有错误。目前的代码如下所示:

export class ErrorNotificationService {
  public addError: BehaviorSubject<ErrorNotification> = new BehaviorSubject(null);
  public removeErrorById: BehaviorSubject<string> = new BehaviorSubject(null);
  public removeErrorById: BehaviorSubject<string> = new BehaviorSubject(null);

  public createNotification(pid: string,
                            message: string,
                            key: string,
                            displayContact: boolean,
                            errorCode: string = null): void {
    this.addError.next(new ErrorNotification(pid, message, displayContact, errorCode, key));
  }

  public dismissNotification(pid: string, key: string): void {
    this.removeErrorByIdentity.next(`${pid}_${key}`);
  }

  public dismissAllNotifications(pid: string): void {
    this.removeErrorById.next(pid);
  }
}

这就是我们订阅BehaviorSubject(s) 的方式:

  private subscribeToErrorService(): void {
    this.errorService.addError.subscribe(
      (error) => {
        this.addNewError(error);
      }
    );
    this.errorService.removeErrorById.subscribe(
      (id) => {
        this.deleteErrorById(id);
      }
    );
    this.errorService.removeErrorByIdentity.subscribe(
      (identity) => {
        this.deleteErrorByIdentity(identity);
      }
    );
  }

这是跟踪错误的组件代码:

  public currentErrors: ErrorNotification[] = [];

  public deleteErrorById(id: string): void {
    if (id !== null) {
      this.currentErrors = this.currentErrors.filter( (error) => error.getId() !== id);
    }
  }

  public deleteErrorByIdentity(identity: string): void {
    if (identity !== null) {
      this.currentErrors = this.currentErrors.filter( (error) => error.getIdentity() !== identity);
    }
  }

  private addNewError(error: ErrorNotification): void {
    if (error !== null) {
      this.currentErrors.push(error);
    }
  }

delete...和方法从保存错误的add...数组中删除/添加。我有一个ngOnDestroy()方法要清除该页面(pid)创建的所有错误。问题是,当有多个错误时,我们似乎只从BehaviorSubject. dismissAllNotifications行为不符合预期。我似乎无法想出一种方法来迭代removeErrorById以消除所有错误。

我希望这是有道理的。我仍在尝试自己理解这段代码,所以我不知道我的问题是否清楚。事实上,我什至不确定这个设计是否按预期工作!谢谢你的帮助。

PS - 如果我要被否决,如果有人能告诉我为什么会很棒......

标签: angularobservable

解决方案


推荐阅读