angular - 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 - 如果我要被否决,如果有人能告诉我为什么会很棒......
解决方案
推荐阅读
- php - PHP - 只有在迭代之间发生变化时才循环遍历数组并打印出值
- android - 从文件描述符上的相机错误返回图像
- python - 如何在菜单栏中实现刷新按钮以刷新所有组合框项的原始状态?
- python - Keras LSTM 拟合欠拟合
- javascript - Angular:使用 ControlValueAccessor 自定义输入
- python - 如何将行数堆叠到一行并分配id
- mongodb - .gitlab-ci.yml 中的 Mongodb 副本集
- epplus - 如何使用 EPPlus 创建小计
- animation - “擦除效果”是如何智能实现的,动画方向从左到右淡入
- javascript - 在javascript中减少base64图像保持纵横比的尺寸