gpt4 book ai didi

javascript - Firebase - 在删除项目时调用 child_added

转载 作者:行者123 更新时间:2023-12-03 01:38:36 24 4
gpt4 key购买 nike

我有一个 post 列表,我正在使用 .on('child_add') 获取它们,问题是我只想获取 post 是在添加项目时发布的,而不是在删除项目时发布的,但是,似乎 .on('child_added')即使帖子被删除, 也会被调用。这不是我所需要的。

这是我的功能:

if(fromClick) { this.subscription.off(); this.firstRun = true;}
this.postFeed = new Array();
this.subscription = this.database.database.ref('/posts/'+this.locationId)
.orderByChild('created')
.limitToLast(10);

this.subscription.on('child_added', (snapshot) => {
this.postFeed.push(snapshot.val());
});

因此它显示最后一个10,然后当添加一个项目时,它也会将其添加到数组中,但是当删除一个项目时,它会再次被调用。

如何防止这种情况发生?这样调用只发生在添加的 post 上?

最佳答案

如果您调用:

this.database.database.ref('/posts/'+this.locationId)
.orderByChild('created')
.limitToLast(10);

您正在创建一个包含 10 个最新帖子的查询。如果您删除其中一篇文章,另一篇文章将成为最新的第 10 篇帖子,因此您将获得一个 child_added

我唯一能想象的就是只获取 10 一次,然后执行 limitToLast(1):

this.database.database.ref('/posts/'+this.locationId)
.orderByChild('created')
.limitToLast(10)
.once("value", function(snapshot) {
snapshot.forEach(function(child) {
// These are the initial 10 children
});
});
this.database.database.ref('/posts/'+this.locationId)
.orderByChild('created')
.limitToLast(1)
.on("child_added", function(snapshot) {
// This is the latest child, but this will also fire when you remove the current latest
});

关于javascript - Firebase - 在删除项目时调用 child_added,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50957140/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com