AngularFire 0.82 - How to request denormalized data?

This question is similar to AngularFire - how do I request denormalized data? but I really need an answer that uses AngularFire (current version 0.82). This is an example of the data structure used:

{ "users": { "user1": { "name": "Alice", "lists": { "list1": "true" } }, "user2": { "name": "Bob", "lists": { "list2": "true" } } }, "lists": { "list1": { "title": "Example" }, "list2": { "title": "Example2" } } } 

or, in different notations: to get all user lists, we need all of this:

 users/$userID/lists/$listID 

and the contents of the lists are stored in:

 lists/$listID 

What I want to achieve is access to the contents of certain user lists, but without the "manual" iteration over each $ ListID.

An even nicer answer might include code that wraps this access in an advanced AngularFire service, similar to the code in the section called “Creating AngularFire Services” on AngularFire docs

0
source share
1 answer

This would help (as it always happens) to understand the use case that we are trying to solve, and not just the solution you chose for this problem - there are often simpler ways to approach the set of problems (see What is the XY problem? ).

There is nothing in AngularFire to handle nested list lists. A list of specific items will actually be a little simpler than a few lists that the list refers to.

Firebase.util

A tool called Firebase.util exists to help with denormalization (it is currently getting revved to V2, which should come out in a month or two), and it is compatible with AngularFire:

 var fbRef = new Firebase(URL); var indexRef = fbRef.child('users/' + userId + '/lists'); var dataRef = fbRef.child('lists'); var joinedRef = Firebase.util.intersection(indexRef, dataRef); var lists = $firebase( joinedRef ).$asArray(); 

Angular only

An angular - the only approach is to load lists manually and use AngularFire for individual lists:

 app.factory('NestedList', function($firebase, $timeout) { return function(indexRef, dataRef) { var hashOfLists = {}; indexRef.on('child_added', function(snap) { var key = snap.key(); var list = $firebase( dataRef.child(key).$asArray(); hashOfLists[key] = list; }); indexRef.on('child_removed', function(snap) { $timeout(function() { delete hashOfLists[snap.key()]; }); }); return hashOfLists; } }); 

note that this example uses snap.key (), but this only applies when using the 2.x SDK version, which was released only this week; prev versions should use snap.name ()

For more complex operations and creating your own directives or services, check out the question and answer here . Although this may not seem at first glance, this is a fairly detailed discussion of how to receive any Firebase data and convert it to any proprietary structure.

+3
source

All Articles