首页 > 解决方案 > 我正在订阅订阅并使用 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>

标签: angularrxjs

解决方案


好像没有清零有误followedPostsArray。解释给出的代码和您的额外订阅我猜想您在添加要关注的新帖子时重新加载所有帖子。

您必须先重置阵列。我仍然不知道您的跟随按钮调用哪种方法,所以我即兴使用了一个符号名称。

followPost() {
    // reset the array
    this.followedPostsArray = [];

     // only then call the service
     this.postService.getFollowedPosts(...);
}

这应该可以阻止您重复输入。


推荐阅读