使用 Observable 时防止重复插入 Angular 2
Preventing duplicates inserted when using Observable Angular 2
我遇到一个问题,每次提交 post 时,我的数组都会呈指数级增长。我认为它发生在第二个可观察对象中,因为在每个 post 之后更新用户对象以更新他们上次更新 post.
时的时间戳
我正在尝试检查内部可观察对象是否 post 已经在数组中,以防止将重复项插入到数组中。由于某种原因,这不起作用。
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;
}
}
你的问题是,通过创建一个新的 PostContainer
,你正在创建一个不在 container
中的新对象,因此它将添加 posts
中的每个 post
].
您应该检查 post
的某些唯一值是否存在于 container
的任何项目中
类似于:
if (container.findIndex((postContainer) => postContainer.id === post.id) === -1) {
continer.push(new PostContainer(post, x[0].equippedItems));
}
我不确定你对这个问题的看法是否正确,像这样从你的帖子中删除重复项很容易:
this.postsService.subscribeAllPosts(this.selectedArea)
.distinct()
.subscribe(posts => {
...
});
我遇到一个问题,每次提交 post 时,我的数组都会呈指数级增长。我认为它发生在第二个可观察对象中,因为在每个 post 之后更新用户对象以更新他们上次更新 post.
时的时间戳我正在尝试检查内部可观察对象是否 post 已经在数组中,以防止将重复项插入到数组中。由于某种原因,这不起作用。
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;
}
}
你的问题是,通过创建一个新的 PostContainer
,你正在创建一个不在 container
中的新对象,因此它将添加 posts
中的每个 post
].
您应该检查 post
的某些唯一值是否存在于 container
类似于:
if (container.findIndex((postContainer) => postContainer.id === post.id) === -1) {
continer.push(new PostContainer(post, x[0].equippedItems));
}
我不确定你对这个问题的看法是否正确,像这样从你的帖子中删除重复项很容易:
this.postsService.subscribeAllPosts(this.selectedArea)
.distinct()
.subscribe(posts => {
...
});