使用 NGXS 删除 Angular 中嵌套数据的对象
Deleting an object of a nested data in Angular using NGXS
我已经在我的 Angular 应用程序中成功实现了 post 的获取和删除功能。当您想删除 post 中的评论时,我的问题就来了。我正在尝试使用 NGXS 来实现它。我将如何能够在 post 中访问它,以便我可以检索评论以便能够将其删除。
这是我所做的
CODE
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
});
}
要从 post 中删除评论,您必须先 指定要从哪个 post 中删除评论:
// 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的state operators更新你的状态(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)
}))
}));
}
这里是link到updated stackblitz
我已经在我的 Angular 应用程序中成功实现了 post 的获取和删除功能。当您想删除 post 中的评论时,我的问题就来了。我正在尝试使用 NGXS 来实现它。我将如何能够在 post 中访问它,以便我可以检索评论以便能够将其删除。 这是我所做的
CODE
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
});
}
要从 post 中删除评论,您必须先 指定要从哪个 post 中删除评论:
// 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的state operators更新你的状态(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)
}))
}));
}
这里是link到updated stackblitz