首页 > 解决方案 > 从数组中删除项目时如何使用behaviorSubject

问题描述

我有 Angular 8 应用程序。

我有两个组成部分,比如孩子 - 父母的关系。因此,我从子项中删除了该项目,但该项目在父项(项目列表)中仍然可见。只有在页面刷新后,该项目才会从列表中消失。

所以我有这个服务:

export class ItemListService {
 _updateItemChanged = new Subject<any>();
 _removeItemChanged = new BehaviorSubject<any>([]);

  constructor() {}
}

这是 item.ts - 孩子:

openRemoveDialog() {
    const dialogRef = this.dialog.open(ItemRemoveDialogComponent, {
      width: '500px',
      height: '500px',
      data: {
        dossierId: this.dossier.id,
        item: this.item,
        attachments: this.item.attachments
      }
    });

    this.itemListService._removeItemChanged.next(this.item.title);

    dialogRef.afterClosed().subscribe(result => {
      if (result === true) {
        this.router.navigate(['/dossier', this.dossier.id]);

      }
    });
  }

这是 view.ts(item list) - parent:所以在这个组件中必须进行刷新



 ngOnInit(): void {
    this.show = !this.router.url.includes('/item/');

    this.itemlistService._updateItemChanged.subscribe(data => {
      const index = this.dossierItems.findIndex(a => a.id === data.id);
      this.dossierItems[index] = data;
    });

    this.itemlistService._removeItemChanged.subscribe(data => {
     // this.dossierItems.pop(); What I have to fill in here?

    });

那么我必须改变什么?

谢谢

这是删除功能:

  remove() {
    this.dossierItemService.deleteDossierItem(this.data.dossierId, this.data.item.id)
      .subscribe(() => {
        this.dialogRef.close(true);
      }, (error) => {
        const processedErrors = this.errorProcessor.process(error);
        this.globalErrors = processedErrors.getGlobalValidationErrors();
    });
  }

我现在有这样的:

remove() {
    this.dossierItemService.deleteDossierItem(this.data.dossierId, this.data.item.id)
      .subscribe(() => {
        this.dialogRef.close(true);
        this.itemListService._removeItemChanged.next(true);
      }, (error) => {
        const processedErrors = this.errorProcessor.process(error);
        this.globalErrors = processedErrors.getGlobalValidationErrors();
    });
  }

在 view.ts 中,像这样:

 ngOnInit(): void {
  this.itemlistService._removeItemChanged.subscribe(update => update === true ? this.dossierItems : '');
}

但仍然不会刷新列表

标签: javascriptangulartypescriptrxjsangular-observable

解决方案


您需要为您的数组创建一个新引用,以便 Angular 像这样更新屏幕

this.itemlistService._removeItemChanged.subscribe(data => { 
    // this.dossierItems.pop(); What I have to fill in here?
    this.dossierItems = this.dossierItems.filter(e => e.title !== data);
});

推荐阅读