40

I am trying to understand the concept of factory and service in Angular. I have the following code under the controller

init();

    function init(){
        $http.post('/services', { 
            type : 'getSource',
            ID    : 'TP001'
        }).
        success(function(data, status) {
            updateData(data);
        }).
        error(function(data, status) {

        });

        console.log(contentVariable);
    };
    function updateData(data){
        console.log(data);
    };

This code works fine. But when i move $http service into factory, i am not able to return data back to controller.

studentApp.factory('studentSessionFactory', function($http){
    var factory = {};
    factory.getSessions = function(){
        $http.post('/services', { 
            type : 'getSource',
            ID    : 'TP001'
        }).
        success(function(data, status) {
            return data;
        }).
        error(function(data, status) {

        });
    };
    return factory;
});

studentApp.controller('studentMenu',function($scope, studentSessionFactory){
    $scope.variableName = [];
    init();
    function init(){
        $scope.variableName = studentSessionFactory.getSessions();
        console.log($scope.variableName);
    };
});

Is there any advantage to using factory, since $http works even under controller

2 Answers 2

92

The purpose of moving your studentSessions service out of your controller is to achieve separation of concerns. Your service's job is to know how to talk with the server and the controller's job is to translate between view data and server data.

But you are confusing your asynchronous handlers and what is returning what. The controller still needs to tell the service what to do when the data is received later...

studentApp.factory('studentSession', function($http){
    return {
        getSessions: function() {
            return $http.post('/services', { 
                type : 'getSource',
                ID    : 'TP001'
            });
        }
    };
});

studentApp.controller('studentMenu',function($scope, studentSession){
    $scope.variableName = [];

    var handleSuccess = function(data, status) {
        $scope.variableName = data;
        console.log($scope.variableName);
    };

    studentSession.getSessions().success(handleSuccess);
});
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks Brian. Makes sense now. I get a missing } error after property list error. Error persists after closing adding a close paranthesis for return in factory.
Oki fixed the paranthesis part. Now the code is studentApp.factory('studentSession', function($http){ return { getSessions: function() { return $http.post('/services', { type : 'getSource', ID : 'TP001' }); } } }); Now got an error stating Error b is not a function. I dont have any function called b. Any suggestion on what triggers this error?
Thanks. I missed that brace. As for the "b is not a function", are you using some sort of code minification or uglification?
Im using minified angularjs. will try out changing to normal version. thnx
Awesome, thanks for this... exactly the concept I've been trying to get my head around.
|
10

The first answer is great but maybe you can understand this:

studentApp.factory('studentSessionFactory', function($http){
    var factory = {};

    factory.getSessions = function(){
        return $http.post('/services', {type :'getSource',ID :'TP001'});
    };

    return factory;
});

Then:

studentApp.controller('studentMenu',function($scope, studentSessionFactory){
      $scope.variableName = [];

      init();

      function init(){
          studentSessionFactory.getSessions().success(function(data, status){
              $scope.variableName = data;
          });
          console.log($scope.variableName);
     };
 });

1 Comment

Looks like a good answer, but .success has now been deprecated it seems stackoverflow.com/questions/33531336/….

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.