首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在使用可观测角度2时防止重复插入

在使用可观测角度2时防止重复插入
EN

Stack Overflow用户
提问于 2016-12-14 19:23:22
回答 2查看 1.1K关注 0票数 0

我有一个问题,我的数组是指数增长,越来越多,每次我提交一篇文章。我认为这发生在第二个可观察到的位置,因为用户对象在每个帖子之后被更新,以更新时间戳,以便他们最后一次更新帖子。

我试图检查内部可观察到的帖子是否已经在数组中,以防止重复的内容被插入到数组中。由于某种原因,这是行不通的。

代码语言:javascript
复制
 loadPosts(url: string) {
    switch (url) {
        case '/timeline/top':
            this.postsService.subscribeAllPosts(this.selectedArea)
                .subscribe(posts => {
                    let container = new Array<PostContainer>();
                    for (let post of posts) {
                        this.getEquippedItemsForUsername(post.username).subscribe(x => {
                                try {
                                    if (container.indexOf(new PostContainer(post, x[0].equippedItems)) === -1) {
                                        container.push(new PostContainer(post, x[0].equippedItems));
                                    }
                                     console.log( container); // grows exponentially after each submitted post
                                } catch (ex) { }
                            }
                        );
                    }
                    this.postContainers = container; // postContainers is the array that is being looped over in the html.
                });
            break;
   }

}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-12-14 19:52:04

您的问题是,通过创建一个新的PostContainer,您将创建一个不在container中的新对象,因此它将在posts中添加每个post

相反,您应该检查post的某些唯一值是否存在于container的任何项中。

类似于:

代码语言:javascript
复制
if (container.findIndex((postContainer) => postContainer.id === post.id) === -1) {
    continer.push(new PostContainer(post, x[0].equippedItems));
}
票数 2
EN

Stack Overflow用户

发布于 2016-12-14 19:54:19

我不确定你是否对这个问题是正确的,从你的帖子中删除重复的内容很容易:

代码语言:javascript
复制
this.postsService.subscribeAllPosts(this.selectedArea)
            .distinct()
            .subscribe(posts => {
                ...
            });
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41150563

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档