AngularJS / factory controller returns undefined object

Angular Controller result undefined after factory calming web api call. I have seen many posts about this, but none seem to solve my problem. I have a controller that makes a quiet api2 call on the network. Using fiddler, I can see the call made and the 200 response, but I can never get the results, and I know the get is happening via async. Below is the factory and controller. I've also tried to explicitly send a callback to the factory, this approach even results in an undefined object, just doesn't work. Im really dormant here and Im new to Angularjs, what's wrong? I currently have a controller call connected to a button for explicit testing.

**FACTORY NO EXPLICIT CALL-BACK** 
casenoteApp.factory('MyFactory', function ($http) {


var factory = {};

var urlBase = 'http://xxxxxx/api/Client';


factory.getClients = function (userLogin) {

    return $http.get(urlBase + '/' + userLogin);
};


return factory;
});

**CONTROLLER NO EXPLICIT CALL-BACK** 
casenoteApp.controller('MyController', MyController);

function MyController($scope, MyFactory) {


$scope.addCustomer = function () {

    MyFactory.getClients(123456)
       .success(function (clients) {

            var curCust = clients;
            $scope.status = clients.last_name;

        })
       .error(function (error) {
           $scope.status = 'Unable to load client data: ' + error.message;
       });        

}


}

**FACTORY PASSING IN CALL-BACK**
casenoteApp.factory('MyFactory', function ($http) {


var factory = {};

var urlBase = 'http://xxxxxx/api/Client';

factory.getClients = function (userLogin, callback) {

    return $http.get(urlBase + '/' + userLogin).success(callback)

}

return factory;
});


**CONTROLLER PASSING IN CALL-BACK**
casenoteApp.controller('MyController', MyController);

function MyController($scope, MyFactory) {


$scope.addCustomer = function () 



    MyFactory.getClients(123456, function(clients) {

            var curCust = clients[0];
            $scope.status = clients.last_name;
        })


}

}

      

+3


source to share


1 answer


Set up your factory for use .then

and return data like:

casenoteApp.factory('MyFactory', function ($http) {
    var urlBase = 'http://xxxxxx/api/Client';

    return {
        getClients: function (userLogin) {
            return $http.get(urlBase + '/' + userLogin).then(function(data) {
                return data.result;
            });
        }
    };
});

      



And your controller:

MyFactory.getClients(01234).then(function(data) {
    console.log(data); //hello data!
});

      

+6


source







All Articles