1

我已经在我的 Angular 应用中成功实现了 post 的获取和删除功能。当您想删除帖子中的评论时,我的问题就来了。我正在尝试使用 NGXS 来实现它。我将如何能够在帖子中访问它,以便我可以检索评论以将其删除。这是我所做的

看到这个链接

代码

onDeleteComment(id: number){
    this.store.dispatch(new DeleteComment(id));
}



 @Action(DeleteComment)
  deleteComment(
    { getState, setState }: StateContext<PostStateModel>,
    { id }: DeleteComment
  ) {
    const state = getState();
    const filteredArray = state.posts.filter(item => item.id !== id);
    setState({
      ...state,
      posts: filteredArray
    });
  }
4

1 回答 1

1

要从帖子中删除评论,您必须首先指定要从哪个帖子中删除评论:

// app.component.ts
onDeleteComment(postId: number, commentId: number){
  this.store.dispatch(new DeleteComment(postId, commentId));
}

下一步是更新您的DeleteComment操作以接受新参数:

// post.action.ts
constructor(public readonly postId: number, public readonly commentId: number) { }

最后,在ngxs的状态操作符( patch, updateItem, )的帮助下更新你的状态removeItem

@Action(DeleteComment)
deleteComment(
  { getState, setState }: StateContext<PostStateModel>,
  { postId, commentId }: DeleteComment
) {
  const state = getState();

  setState(patch<PostStateModel>({
    // firstly, you're modifying the post by removing a comment from it
    posts: updateItem<Post>(p => p.id === postId, patch<Post>({
      // secondly, you remove the comment itself
      comments: removeItem<Comment>(c => c.id === commentId)
    }))
  }));
}

这是更新的 stackblitz的链接

于 2019-11-22T16:06:42.490 回答