我有一个帖子部分,用户可以在其中添加评论和回复。我已将分页逻辑应用于帖子部分。当页面加载第一页的初始 5 条记录时,我正在显示。然后我有重新加载按钮,点击它时,第二页的下 5 条记录会从 api 获取并附加(concat
使用)到以前的结果中,就像发生的那样。每次点击重新加载按钮时,我都会调用getallpost
函数,添加评论/回复以从 api 获取更新的条目/数据。
getallpost
功能。
getallpost() {
this.formData = new FormData();
this.formData.append("page", this.pageNumber);
this.formData.append("perpage", this.perPageRecords);
this.postService.getAllEventsPost(this.formData).subscribe((result) => {
if (result['status'] === false) {
} else {
this.totalRecords = result.data.pagination.totalRecords;
this.lastPage = result.data.pagination.LastPage;
this.selectedpost = this.selectedpost.concat((result as any).data.data);
this.selectedpost.map((item) => {
item.show = false;
item.isReadMore = true;
item.isShow = true;
});
}
});
}
pageNumber = 1
, perPageRecords = 5
,selectedpost = []
被定义。
关于Relaod按钮的点击功能如下。
onReloadbuttonClick() {
this.pageNumber++;
this.getallpost();
}
当评论/回复被添加时,功能如下
onSubmit(post_id) {
this.loading = true;
if (this.f.comment.value) {
this.postService
.addPostComment(this.id, post_id, this.f.comment.value)
.subscribe((data) => {
if (data['message'] === 'Token is Expired') {
this.loading = false;
this.authService.logout();
} else {
if (data['status'] === false) {
if (data['errors']) {
console.log(data['errors'][0].comment);
}
this.loading = false;
} else {
this.form.reset();
this.getallpost();
this.notifyService.showSuccess(
'Comment added successfully!!',
''
);
this.loading = false;
}
}
});
} else {
this.notifyService.showWarning('Please enter the comment.', '');
this.loading = false;
return;
}
}
重新加载按钮按预期工作。我面临的问题是当我添加评论/回复时,它会被添加并显示成功消息。但是即使我正在调用getallpost
函数,我添加的评论也不会显示在这一点上。
由于 this.selectedpost = this.selectedpost.concat((result as any).data.data);
这一行,当前页码值新的更新数据被再次获取并附加,而不是被新的更新数据替换。意味着例如最初获取了 5 条第一页记录。在将评论添加到其中一个帖子后getallpost
,调用函数并再次调用第一页的 5 条记录,并添加相应的更新帖子并添加评论。理想情况下,只有数据应该被更新而不应该被附加。
this.selectedpost
在上述情况下添加评论/回复后,我应该应用哪种逻辑来获取更新的记录,而无需重新加载/刷新页面(例如不使用location.reload
等)?
我已经尝试了一些逻辑,但这些逻辑没有按预期使用重新加载按钮。
请指导和帮助。谢谢。