【问题标题】:How to delete attachment from the attachment object array inside another comment object array which is inside another object array如何从另一个对象数组中的另一个注释对象数组中的附件对象数组中删除附件
【发布时间】:2022-01-10 08:36:36
【问题描述】:

我想从附件对象数组中删除附件,该附件对象数组位于另一个对象数组内的另一个注释对象数组内。我一直在努力解决这个问题。

export class CommentSection{
  id: string;
  comments: CommentObject[];
}
export class CommentObject{
  id: string;
  created: Date;
  text: string;
  attachments: CommentAttachment[];
}
export class CommentAttachment{
  id: string;
  created: Date;
  filename: string;
}

我的 ts 文件包含解决方案草案,但无法正常工作(不删除附件):

export class CommentsComponent {

  public comment: CommentObject;
  commentsArray: CommentSection;

  public deleteCommentAttachment(attachment: CommentAttachment): void {
    this.commentsArray.comments = this.commentsArray.comments.filter((c) =>
      c[this.comment.id].attachments.splice(attachment.id, 1),
    );
  }
}

【问题讨论】:

    标签: angular typescript object


    【解决方案1】:

    你也可以转换成 rxjs 来以可读的步骤来做,虽然有些人可能会觉得它有点矫枉过正。示例如下:

    https://stackblitz.com/edit/angular-ivy-swnhf1?file=src%2Fapp%2Fapp.component.ts

    【讨论】:

      【解决方案2】:

      您想过滤附件而不是 cmets 对吗? splice 还使用索引而不是自定义 id-s。我已经用地图替换了过滤器。还没有测试过,但它应该可以工作:)

      this.commentsArray.comments = this.commentsArray.comments.map((c) => {
          const comment = c[this.comment.id];
          const attachments = comment.attachments;
          const index = attachments.findIndex(at => at.id == attachment.id);
          attachments.splice(index, 1);
        });
      

      【讨论】:

      • 谢谢!如果出现错误,您知道如何修改代码:Type 'void[]' is not assignable to type 'CommentObject[]'?
      • 我在您的示例中没有看到该代码,但这通常意味着某些东西需要类型 CommentObject[] 并且您返回 void[](什么都没有)。第一个选项是更正这两种类型并返回正确的类型。第二种选择是使用任何返回类型
      猜你喜欢
      • 2019-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多