0

I have following controller code

module.registerController('DemoCtrl', function ($scope, myFactory) {
        myFactory.get(function (data) {
            console.log(data); /// data is always undefined 
        });
    });

and following the factory which is calling restful webapi

module.registerFactory('myFactory', ['$http',
    function ($http) {
            function get(callback) {
                $http.get('mywebapiurl')
                    .success(function (response) {
                        //debugger; data comes back from server
                        callback(response);
                    }).error(function (response, status, headers, config) {
                        callback(response);
                    });
            }

        return {
            get: get
        }
    }]);

The factory is calling webapi service and does gets the data back. However in controller the data doesnt get returned.

Am I missing something obvious here? Also not sure if this is the best way to call webservice in angularjs in controller using factory. Any inputs are most welcome.

Thanks,

1
  • try myFactory.get().then(function(data){ }) Commented Aug 13, 2015 at 7:33

2 Answers 2

1

You want to return a promise instead of passing a callback. As $http.get already returns a promise, you can just return that, or a derived promise that returns the response data directly. By the way, your factory looks like it should be a service instead:

angular.moudule('yourApp')
.service('myService', ['$http', myService]);

function myService($http) {
    this.get = function(url) {
        return $http.get(url)
                   .then(function transformData(response){
                       return response.data;
                   }).catch(function onError(rejectionResponse){
                       //Whatever you want to do here
                   });
    }
}

This way myService.get will return a promise you can .then(), .catch() and .finally() on what you want, staying in the frameworks coding style. For example:

var squirrels = [];
myService.get('http://squirrelshop.com/api/squirrels')
    .then(function(squirrelsData){
        console.log('Got the squirrels!');

        squirrels = squirrelsData;
    }).catch(function(rejection){
        console.warn('Couldnt fetch squirrels. Reason: ' + rejection);
    });
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks the promise does seems a better way of doing this. Could you please post a sample code with using promise. I was also a bit uneasy about using callback. thanks
@activebiz I did. I recommend to do some research on promises and their syntax, theyre quite elegant, but explaining how exactly all off this works would be a bit too broad for an SO answer ;-)
1

controller code

module.registerController('DemoCtrl', function ($scope, myFactory) {
    myFactory.get("url").then(function(d) {
            console.log(d.data); 
        }
    });
});

factory which is calling restful webapi

module.registerFactory('myFactory', ['$http',
function ($http) {
         var apiFactory = {
               get:function(url){
                   return $http.get(url);
               }
         }
    return apiFactory;
}]);

Success and failure in factory

module.registerFactory('myFactory', ['$http',
function ($http) {
     var apiFactory = {
           get:function(url){
               return $http.get(url).then(function(response){
                      // success
                      return responce.data;
               },function(error){
                      //failure
                      return error;
               };
           }
     }
    return apiFactory;
}]);

2 Comments

Is it possible to keep the success and failure code in factory?
Yes, its possible, let me add this in my answer.

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.