我有一個網站,我想通過Firebase添加文章,我想出了以下代碼,顯示文章的摘要,但這是一些由用戶創建的文章,我想修改它以顯示所有由其他用戶創建的文章
function allIndex(){
firebase.auth().onAuthStateChanged(function(user) {
user ? firebase.database().ref(user。 displayName).child("Post")。 orderByChild("upedAt") 。 on("value"/span>, function(user) {
var t = ""/span>;
user.forEach(function(user) {
entry = user.val(), t = '<div class="article"><a href="my-posts.html?id='/span> user. getKey() '"><div class="panel-heading">' excerpt(條目。 title, 140) '</div><div class="panel-body"><small>' datetimeFormat(條目。 updatedAt) '</small></div></a>< small class="'/span> entry. status '">' entry.status "</small></div> " t
}), $("#entries.post").removeClass("loading").find(" 。 loader").remove(), $("#entries.post .panel_content") .append(t)
}) : (alert("請先登錄"), window. location.href = "sign-in.html" )
})
}
2
uj5u.com熱心網友回復:
看起來你有一個這樣的結構:
span class="hljs-attr">$userName: {
Posts: {
"post1"/span>: { ... },
"post2"/span>: { ... },
...
}
}
現在你正在加載一個特定用戶的帖子,并將它們添加到HTML中。要加載所有用戶的帖子,你需要:
- 從你的資料庫中高一級的位置加載資料。
- 然后在您的回呼中回圈處理每個用戶。
firebase.database().ref()。 on("value"/span>, function(users) {
var t = ""/span>;
users.forEach(function(user) {
user.val().Posts.forEach(function(post){
...在這里處理帖子
})
})
})
你會注意到,我們不再按updatedAt排序,因為在你的網站中無法做到這一點。
你會注意到,我們不再按updatedAt排序,因為在你目前的資料結構中不可能跨越所有用戶。如果你想通過updatedAt來顯示所有用戶的所有帖子,可以考慮將你的資料結構改為一個扁平的帖子串列,而用戶名則是每個帖子的一個屬性:
Posts: {
"post1": { username: "...", ... },
"post2": { username。"...", ... },
...
}
uj5u.com熱心網友回復:
是的,我使用這種結構,因為我是用下面的代碼來寫的
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 push(e).then(function(e){
window.location.href = "my-posts.html?id="/span> e.getKey()
}).catch(function(e) {
alert(e), console.error(e)。
}), !1.
})) : (alert("請先登錄"), window. location.href = "sign-in.html" )
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/325756.html
標籤:
