javascript - 查看 Firebase 上的所有成员文章!Javascript 网页应用
问题描述
我有一个网站,我想通过 Firebase 添加文章,我想出了以下显示文章摘要的代码,但它是用户创建的一些文章,我想修改它以显示由创建的所有文章其他用户
function allIndex(){
firebase.auth().onAuthStateChanged(function(user) {
user ? firebase.database().ref(user.displayName).child("Posts").orderByChild("updatedAt").on("value", function(user) {
var t = "";
user.forEach(function(user) {
entry = user.val(), t = '<div class="article"><a href="my-posts.html?id=' + user.getKey() + '"><div class="panel-heading">' + excerpt(entry.title, 140) + '</div><div class="panel-body"><small>' + datetimeFormat(entry.updatedAt) + '</small></div></a><small class="' + entry.status + '">' + entry.status + "</small></div>" + t
}), $("#entries.post").removeClass("loading").find(".loader").remove(), $("#entries.post .panel_content").append(t)
}) : (alert("Please login first"), window.location.href = "sign-in.html")
})
}
这是一些相关的逻辑,可以证明结构的合理性
function create() {
firebase.auth().onAuthStateChanged(function(n) {
n ? (tinymce.init({
}), $("#new_entry").submit(function(e) {
e.preventDefault(), (e = {}).title = $(this).find('[name="title"]').val(), e.description = $(this).find('[name="description"]').val(), e.labels = $(this).find('[name="labels"]').val(), e.content = tinymce.get("content").getContent(), e.createdAt = (new Date).getTime(), e.updatedAt = e.createdAt, e.views = 0, e.status = "Pending";
var t = firebase.database().ref(n.displayName),
a = t.child("Posts");
return t.child("Points").transaction(function(e) {
return (e || 0) + 10
}), a.push(e).then(function(e) {
window.location.href = "my-posts.html?id=" + e.getKey()
}).catch(function(e) {
alert(e), console.error(e)
}), !1
})) : (alert("Please login first"), window.location.href = "sign-in.html")
});
}
解决方案
看起来你有这样的结构:
$userName: {
Posts: {
"post1": { ... },
"post2": { ... },
...
}
}
现在您正在加载来自特定用户的帖子,并将它们添加到 HTML。要加载所有用户的帖子,您需要:
- 从数据库中更高的一级加载数据。
- 然后在您的回调中遍历每个用户。
firebase.database().ref().on("value", function(users) {
var t = "";
users.forEach(function(user) {
user.val().Posts.forEach(function(post) {
... handle post here
})
})
})
您会注意到我们不再订购updatedAt
,因为在您当前的所有用户数据结构中这是不可能的。如果您想通过 显示所有用户的所有帖子updatedAt
,请考虑将您的数据结构更改为帖子的平面列表,其中用户名是每个帖子的属性:
Posts: {
"post1": { username: "...", ... },
"post2": { username: "...", ... },
...
}
推荐阅读
- firebase - Flutter、Firebase、Google AI API 和欧盟 cookie 指令
- amazon-web-services - Cloudfront 路径映射提供内容而不是重定向?
- gerrit - Gerrit send underscore to Uploading Changes message
- c# - 如何根据条件过滤数据表并忽略大小写?
- r - 将R数据框中的矩阵列转换为多列
- python - 创建一个 python 脚本,它将在文本文件中搜索某个键并将数字复制到一个新文件中
- html - HTML/CSS/Javascript 中是否有“广播”方法?
- javascript - RTCPeerConnection addstream 事件未在 firefox 中触发,未聚焦或最小化
- c# - 如何使用 XUnit Dependency Constructor Injection 创建我的具体类
- javascript - 如何使用 async/await 语法重写此请求?