我有一个问题,我的数组是指数增长,越来越多,每次我提交一篇文章。我认为这发生在第二个可观察到的位置,因为用户对象在每个帖子之后被更新,以更新时间戳,以便他们最后一次更新帖子。
我试图检查内部可观察到的帖子是否已经在数组中,以防止重复的内容被插入到数组中。由于某种原因,这是行不通的。
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;
}
}发布于 2016-12-14 19:52:04
您的问题是,通过创建一个新的PostContainer,您将创建一个不在container中的新对象,因此它将在posts中添加每个post。
相反,您应该检查post的某些唯一值是否存在于container的任何项中。
类似于:
if (container.findIndex((postContainer) => postContainer.id === post.id) === -1) {
continer.push(new PostContainer(post, x[0].equippedItems));
}发布于 2016-12-14 19:54:19
我不确定你是否对这个问题是正确的,从你的帖子中删除重复的内容很容易:
this.postsService.subscribeAllPosts(this.selectedArea)
.distinct()
.subscribe(posts => {
...
});https://stackoverflow.com/questions/41150563
复制相似问题