Serving processed $http response from factories,in AngularJS

December 21, 2014
by Rahil Shaikh

This is a short tutorial which 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 organised , 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;
    });
});

For ‘POST’requests, payload or request data can be passed as a function parameter.

In some cases web services return a lot more data then 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 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.

About

Engineer. Blogger. Thinker. Loves programming and working with emerging tech. We can also talk on Football, Gaming, World Politics, Monetary Systems.

Get notified on our new articles

Subscribe to get the latest on Node.js, Angular, Blockchain and more. We never spam!
First Name:
Email:

12 comments

  1. |

    Whats diff between this and a service?

    • |

      Hi Geilt,
      Factories and services more or less could be used to achieve similar stuff.
      Factories are preferred over services where logic becomes a bit complicated.
      Factories are injectable function that can return stuff.
      For eg: If you inject a factory into an controller , whatever is returned by the factory is accessible to the controller .
      Services are constructor function that can be injected.
      For eg : If you inject a service into a controller,whatever was defined on the ‘this’ keyword inside the service is accessible to the controller.

      Thanks for your comment , hope i cleared your doubt.

  2. |

    Hi, Rahil Shaikh, thanks for your post.

  3. Hatem
    |

    You save my life man !! thank’ you a lot !

  4. Amsidh Lokhande
    |

    Thanks a lot. You saved my big time.

  5. Ron
    |

    Awesome, such a small article tutorial, but so helpful. Saved my day!!

  6. Martin
    |

    Nice one, clear and concise and straight to the point. I was always wondering about this concept of using a factory to perform a $http service – thanks!

  7. Alberto
    |

    You are the best !!!
    I got the point!!!
    Muchas Gracias.

  8. |

    Hi, Great Post!!!
    I have a question.. How should we manage the errors from the API response. I am just not able to figure this out.
    Should i return a null to the controller?

Leave a Comment