angular - 我正在订阅订阅并使用 Angular 6 在我的视图中获取重复项目我不知道为什么
问题描述
我把代码放在下面。我有一个帖子服务,可以关注和取消关注帖子,并将它们的 id 添加到一个 Observable 数组中。我正在根据需要让项目显示在视图中,但是当我推送到 followPostsArray 时,它将推送 1 + 每个可能已经在 followPostsArray 中的项目。
此外,当我取消关注时,视图不会改变。
组件.ts
this.postService.getFollowedPosts().subscribe((followedPosts) => {
followedPosts.forEach((postId) => {
this.frApiService.GetPostById(postId).subscribe((post) => {
this.followedPostsArray.push(post);
console.log(this.followedPostsArray);
});
});
});
组件.html
<div class="item lib-flex" *ngFor="let post of followedPostsArray; let i = index;">
<div class="title lib-grow" (click)="loadPost(post)">
{{post?.title | shortenContentPipe}}
<span (click)="unfollow(post, $event)">UNFOLLOW</span>
</div>
<div class="time lib-flex lib-main-center lib-cross-center lib-pr5">
<i class="icon icon-Clock lib-mr5"></i>
{{getAge(post?.latestCommentDateTime)}}
</div>
</div>
解决方案
好像没有清零有误followedPostsArray
。解释给出的代码和您的额外订阅我猜想您在添加要关注的新帖子时重新加载所有帖子。
您必须先重置阵列。我仍然不知道您的跟随按钮调用哪种方法,所以我即兴使用了一个符号名称。
followPost() {
// reset the array
this.followedPostsArray = [];
// only then call the service
this.postService.getFollowedPosts(...);
}
这应该可以阻止您重复输入。
推荐阅读
- c - 我们什么时候应该在 C 中使用“外部常量”?
- sharepoint-online - SPO 限制少数选定的文件扩展名
- sql - 根据事件的最短日期将数据分组到不同的表中
- python - python提取域/子域
- python - 请协助开发 Python 装饰器
- javascript - Firebase 的更新功能滞后于浏览器上的按钮点击
- java - Java:在 Android Studio 中替换片段时如何保存用户输入的 EditText 和 TextViews?
- node.js - Material-ui 官方 SSR 示例在生产服务器中不起作用
- hyperledger-fabric - Hyperledger Fabric:可以使用fabric-python-sdk将交易提案转发给另一个节点的背书节点吗?
- mysql - MySQL将分离的月份和年份转换为新字段