Tuesday, February 24, 2015

Creating a Customized Service

In the previous posts on promises, we created a function "onceValuePromise" that would have to be repeated across multiple controllers in a more complete app (yuck).  The solution it to move this function into a customized AngularJS service <https://docs.angularjs.org/guide/services> and inject it into the controllers.

This amounts to creating the following customized service:

JavaScript
// app/services/myFirebase.js
(function() {
angular.module('myApp')
.factory('myFirebase', ['$q', function($q) {
    return {
        onceValuePromise: function (ref) {
            var deferred = $q.defer();
            ref.once('value', function(snapshot) {
                deferred.resolve(snapshot);
            }, function(error) {
                deferred.reject(error);
            });
            return deferred.promise;
        }
    };
}]);
})();
// EOF

And then injecting it into the updated controller as follows (also deleting the unused $q injection and "onceValuePromise" function).

JavaScript
// app/controllers/wineriesCtrl.js
(function() {
angular.module('myApp')
.controller('WineriesCntrl', ['$location','$window', 'myFirebase', function($location, $window, myFirebase) {   
    var ctrl = this;
    var myDataRef;
    ctrl.wineries;
    ctrl.navigate = function(path) {
        $location.path(path);        
    };
    myDataRef = new $window.Firebase('https://wineapp.firebaseio.com');
    myFirebase.onceValuePromise(myDataRef.child('wineries'))
    .then(function(snapshot) {
        ctrl.wineries = Object.keys(snapshot.val()).map(function(key) {
            return {key: key, val: snapshot.val()[key]};
        });
    })
    .catch(function() {
    });
}]);
})();
// EOF

No comments:

Post a Comment