Serving processed $http response from factories,in AngularJS

This is a short tutorial that explains how you can use factories in AngularJs to serve data from web services.

This tutorial will also explain how you can use a factory to return only the required data and not the entire promise.

This practice will keep your code clean and organized, you will also not need to inject $http in each controller.

Most of the developers use the below technique to serve $http calls via factories

Factory
testApp.factory("demoFac", ['$http',function($http){  
    var obj = {};
   
    obj.fetchUserDetails = function(){
        return $http.get('mockjson/userprofile.json');
    }

 return obj;
}]);
Controller
testApp.controller('testCtrl',function($scope,demoFac){
    demoFac.fetchUserDetails().success(function(response){
        $scope.userDetail = response;
    });
});

In some cases, web services return a lot more data than you actually need, or the response from the Web service is not in the same format as you would like to display on the UI or the data you want to display is provided by two separate web-services in parts.
If we return the entire promise from the factory just like we did in the example above we would have to write some logic in our controller to overcome the above-mentioned problems and sometimes this logic can get a bit tacky.
What if we need to display the same data on two different parts of the application under different controllers? You will have to write that tacky logic twice.

View Demo: here
Download Code: here

In some cases, you would require the factory to return only the data that you want.
Below I’ve shown how that can be achieved.

Factory
testApp.factory("demoFac", ['$http',function($http){  
 /*This is an example of how you can process and return the required result*/
    var obj = {};
    obj.getOverallUserInfo = function(){
        return $http.get('mockjson/userprofile.json').then(function(response){   //returns a call back
            this.userDetails = response.data;                                       //store data of 1st call in this.userDetails
            return $http.get('mockjson/userfriendlist.json').then(function(response){ //returns a call back
                this.userDetails.friends = response.data.userfriends;               //Append the response of second call to the data we stored previously
                return this.userDetails;                                    //Return processed result.
            });
        });
    }
 return obj;
}]);
Controller
testApp.controller('testCtrl',function($scope,demoFac){
        demoFac.getOverallUserInfo().then(function(response){ (Notice here we use '.then' as demoFac.getOverallUserInfo() returns a callback)*/
            $scope.requiredInfo = response;
        });
});

See this in action here ,or download the code to get all files.

Facebook
Twitter
LinkedIn
Pinterest

Table of Contents

Related posts