这是场景:我有一个主题列表;每个主题包括帖子;每个帖子都被用户列表“喜欢”了.因此我的数据看起来像这样:
"topics": { "topic1": { "posts": { "post1": true,"post2": true } } },"posts": { "post1": { "title": "An awesome post","likes": { "user1": true } },"post2": { "title": "An even better post","likes": { "user1": true,"user2": true } } },"users": { "user1": { "name": "Mr. T","email": "t@t.com" },"user2": { "name": "Mr. Hello World","email": "hello@world.com" } }
我(我想)知道如何使用Firebase.util(http://firebase.github.io/firebase-util)获取该主题的所有帖子:
Firebase.util.intersection( fb.child('topics').child('topic1').child('posts'),fb.child('posts') )
但现在我希望每篇文章都包含喜欢这篇文章的用户的名字.怎么做到这一点?
可能不会改变任何东西,但这一切都发生在AngularFire中.
解决方法
See working example here
这种非规范化的要点是在抓取帖子时获取用户.它听起来并不复杂.去抓他们吧.
Firebase在内部进行了大量工作以优化请求并为所有侦听器重新使用相同的套接字连接,因此这非常高效 – 几乎没有比下载的字节数更多的开销,无论它们是否被拆分为单独的路径或存储在一起.
HTML:
<h3>Normalizing user profiles into posts</h3> <ul ng-controller="ctrl"> <li ng-repeat="post in posts | orderByPriority" ng-init="user = users.$load(post.user)"> {{user.name}}: {{post.title}} </li> </ul>
JavaScript:
var app = angular.module('app',['firebase']); var fb = new Firebase(URL); app.controller('ctrl',function ($scope,$firebase,userCache) { $scope.posts = $firebase(fb.child('posts')); $scope.users = userCache(fb.child('users')); }); app.factory('userCache',function ($firebase) { return function (ref) { var cachedUsers = {}; cachedUsers.$load = function (id) { if( !cachedUsers.hasOwnProperty(id) ) { cachedUsers[id] = $firebase(ref.child(id)); } return cachedUsers[id]; }; cachedUsers.$dispose = function () { angular.forEach(cachedUsers,function (user) { user.$off(); }); }; return cachedUsers; } });