Last active
January 5, 2018 00:08
-
-
Save katowulf/f78d4a224c06a643ddfa to your computer and use it in GitHub Desktop.
Normalize a "post" record by adding "user" data from another Firebase path in AngularFire
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
app.factory('NormalizedPosts', function($firebaseArray, userCache) { | |
var PostsWithUsers = $firebaseArray.$extend({ | |
// override $$added to include users | |
$$added: function(snap) { | |
// call the super method | |
var record = $firebaseArray.prototype.$$added.call(this, snap); | |
userCache.$load( record.user ).$loaded(function( userData ) { | |
record.userData = userData; | |
}); | |
// return the modified record | |
return record; | |
} | |
}); | |
return PostsWithUsers; | |
}); | |
app.factory('userCache', function ($firebase) { | |
return function (ref) { | |
var cachedUsers = {}; | |
// loads one user into the local cache, you do not need to | |
// wait for this to show it in your view, Angular and Firebase | |
// will work out the details in the background | |
cachedUsers.$load = function (id) { | |
if( !cachedUsers.hasOwnProperty(id) ) { | |
cachedUsers[id] = $firebaseObject(ref.child(id)); | |
} | |
return cachedUsers[id]; | |
}; | |
// frees memory and stops listening on user objects | |
// use this when you switch views in your SPA and no longer | |
// need this list | |
cachedUsers.$dispose = function () { | |
angular.forEach(cachedUsers, function (user) { | |
user.$destroy(); | |
}); | |
}; | |
// removes one user, note that the user does not have | |
// to be cached locally for this to work | |
cachedUsers.$remove = function(id) { | |
delete cachedUsers[id]; | |
ref.child(id).remove(); | |
}; | |
return cachedUsers; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for this, once I move to angularfire 2 & Ionic 2 this can be replaced by Observables right?