angular - 使用 NGXS 在 Angular 中删除嵌套数据的对象
问题描述
我已经在我的 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
});
}
解决方案
要从帖子中删除评论,您必须首先指定要从哪个帖子中删除评论:
// 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)
}))
}));
}
推荐阅读
- javascript - 将带有指定标志图标的网站书签添加到手机主屏幕
- sql - SQL:多个日期的累积行数,包括日期
- xml - 如何从选定 ComboBox 项上的 XML 文件中正确填充文本框?
- java - Android Studio 语法错误
- codeigniter - codeigniter 中的动态数据加载
- javascript - 根据查询更新 Cloud Firestore 中的文档
- php - 运行一个 php 文件
- javascript - chrome 扩展中的声明性内容“移除规则”解释
- bash - 将命令行参数作为文件传递
- django - 如何在 djangos post TestCase 中添加查询字符串?