Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS controller/factory returns undefined object

Angular controller result undefined after factory restful web api call. I’ve seen many posts about this but none seem to solve my problem. I have a controller that makes a restful web api2 call. Using fiddler I can see the call made and the 200 response but I can never seem to get the results, and I know the get is via async. Below is the factory and controller. I’ve also tried to explicitly send the callback into the factory as well, this approach leads to not even an undefined object result, just doesn’t work. I’m really at a standstill here and I’m new to Angularjs, what is wrong? Currently I have the controller call wired 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;
        })


}

}
like image 689
Aaron Lind Avatar asked Jul 18 '26 11:07

Aaron Lind


1 Answers

Setup your factory to use .then and return the data, like so:

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!
});
like image 131
tymeJV Avatar answered Jul 21 '26 02:07

tymeJV



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!