gpt4 book ai didi

angular - 在 Angular NGXS 中访问数组内的嵌套对象

转载 作者:行者123 更新时间:2023-12-05 05:07:31 24 4
gpt4 key购买 nike

我已经在我的 Angular 应用程序中成功实现了删除评论功能。我现在的问题是评论的点赞功能。我如何实现类似的功能。我有变量 is_liked 来确定它是否喜欢。 value = 0 表示不喜欢,value = 1 表示喜欢。请在此处查看我的 stackblitz 链接

PLS CLICK THIS LINK

onLikeComment(data: Comment) {
this.store.dispatch(new LikeComment(data)).subscribe();
}

@Action(LikeComment)
likeComment(
ctx: StateContext<PostStateModel>,
{ payload }: LikeComment
) {
if (payload.is_liked === 1) {
payload.is_liked = 0;
} else {
payload.is_liked = 1;
}
const state = ctx.getState();
ctx.setState(
patch({
post: {
...state.post,
comments: [
...state.post.comments,
updateItem<any>(name => name === payload.id, payload)
]
}
})
);
}

最佳答案

您的代码中存在的主要问题是 updateItem 状态运算符的使用。此运算符需要分配给您传递给 patch 运算符的对象中的字段。

patch({
field1: 'someValue',
comments: updateItem<Comment>(
comment => comment.id === 0,
{id: 0, text: 'This is a nice post!', is_liked: 1}
)
})

updateItem Reference

我看到您的操作处理程序存在的第二个问题是您没有正确使用补丁运算符。此运算符仅允许将值分配给您想要更改的字段,例如 StateContext.patchState

我会将您的代码更改为:

  @Action(LikeComment)
likeComment(
ctx: StateContext<PostStateModel>,
{ payload }: LikeComment
) {
const isLiked = payload.is_liked === 1 ? 0 : 1;

ctx.setState(
patch({
// Apply patch on the post to only update the comments field
post: patch({
// Apply updateItem to make the operator only update the item that matches the condition
comments: updateItem<Comment>(
comment => comment.id === payload.id,
// Apply a patch on the found comment to only change the is_liked field.
patch({is_liked: isLiked}))
})
})
);
}

希望这是有道理的。这是我对 SO 的第一个回答 :)

这是 updated stackblitz

关于angular - 在 Angular NGXS 中访问数组内的嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59015518/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com