简体   繁体   中英

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;
        })


}

}

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!
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM