【问题标题】:Preventing duplicates inserted when using Observable Angular 2防止使用 Observable Angular 2 时插入重复项
【发布时间】:2016-12-14 19:23:22
【问题描述】:

我有一个问题,每次我提交帖子时,我的数组都呈指数级增长。我认为它发生在第二个 observable 中,因为在每个帖子之后都会更新用户对象以更新他们上次更新帖子的时间戳。

我正在尝试检查内部 observable 是否该帖子已经在数组中,以防止将重复项插入到数组中。由于某种原因,这不起作用。

 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;
   }

}

【问题讨论】:

    标签: javascript arrays angular typescript angular2-observables


    【解决方案1】:

    我不确定您对这个问题是否正确,从您的帖子中删除重复内容会很容易,如下所示:

    this.postsService.subscribeAllPosts(this.selectedArea)
                .distinct()
                .subscribe(posts => {
                    ...
                });
    

    【讨论】:

    • @Fred 这是一个很好的提示,我自己没有提到,但重要的是要利用 Observables 的力量而不是重新发明轮子
    【解决方案2】:

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

    您应该检查 post 的某些唯一值是否不存在于 container 的任何项目中

    类似:

    if (container.findIndex((postContainer) => postContainer.id === post.id) === -1) {
        continer.push(new PostContainer(post, x[0].equippedItems));
    }
    

    【讨论】:

      猜你喜欢
      • 2012-08-30
      • 2015-08-07
      • 2016-02-19
      • 1970-01-01
      • 1970-01-01
      • 2020-05-31
      • 2022-01-02
      • 2021-03-27
      • 2021-09-25
      相关资源
      最近更新 更多