1

I have a AngularJS factory 'UserSrvc'. This is responsible for calling a RESTful back end to get and create user accounts using Restangular:

(function () {
    'use strict';

    angular
        .module('myapp')
        .factory('UserSrvc', UserSrvc);

    function UserSrvc(Restangular) {

        return {
            getAllUsers: getAllUsers,
            getUser: getUser,
            saveUser: saveUser
        };

        /////////////////////

        function getAllUsers(){
            return Restangular.all('users').getList();
        }

        function getUser(user){
            return Restangular.setFullResponse(true).one('users', user).get();
        }

        function saveUser(user) {
            return Restangular.all('users').post(user);
        }
    };
})();

My User controller then has functions for initializing the data for loading in to Angular UI Grid as well as functions for saving a user and getting user data:

(function () {
        'use strict';

        var controllerId = 'UserCtrl';

        // Define the controller on the module
        // Inject the dependencies.
        // Point to the controller definition function.
        angular
            .module('myapp')
            .controller(controllerId, UserCtrl, ['UserSrvc', 'ngDialog', '$log', 'toaster']);

        function UserCtrl(UserSrvc, ngDialog, $log, toaster){

            // Using the 'Controller As' syntax, so we assign to the vm variable (for view model).
            var vm = this;

            var allUsers = [];

            // Bindable properties and functions are placed on vm.
            vm.activate = activate;
            vm.allUsers = {};
            vm.toggleForm = false;
            vm.saveUser = saveUser;
            vm.gridOptions = {
                data: allUsers,
                enableSorting: true,
                enableColumnResizing: true,
                enableGridMenu: true,
                showGridFooter: true,
                showColumnFooter: true,
                enableFiltering: true,
                columnDefs: [
                    {name: 'firstName', field: 'First'},
                    {name: 'lastName', field: 'Last'},
                    {name: 'login', field: 'Login'},
                    {name: 'email', field: 'Email'}
                ]
            };

            activate();

            function activate() {
                return getUsers().then(function() {
                    // User Controller is now activated
                    $log.info('UserCtrl activated');
                });
            }

            function refreshUserTable() {
                return UserSrvc.getAllUsers()
                    .then(function(data) {
                        // User table refresh
                        vm.gridOptions.data = data.data;
                        $log.info('User table data refreshed.', vm.gridOptions.data);
                });
            }

            function getUsers() {
                return UserSrvc.getAllUsers()
                    .then(function (data) {
                        $log.debug('data: ', data);
                        vm.gridOptions.data = data;
                        //allUsers = data;
                        $log.debug('allUsers: ', vm.gridOptions.data);
                        return vm.gridOptions.data;
                },
                function(response) {
                    $log.debug("Failed to get users, error with status code", response.status);
                });
            }

            function saveUser(vm) {

                var new_user = {
                        "user": {
                            "First": vm.user.firstname,
                            "Last": vm.user.surname,
                            "Login": vm.user.username,
                            "Password": vm.user.password,
                            "Email": vm.user.email
                        }
                    };

                //$log.debug('The user to be saved: ', user);

                return UserSrvc.saveUser(new_user)
                    .then(function (data) {
                        $log.debug('The user to be saved: ', new_user);
                        $log.debug('response: ', data);
                        // Refresh the table
                        refreshUserTable(vm);
                        // Reset the user form
                        resetForm();
                        // Close the form
                        vm.toggleForm = !vm.toggleForm;
                        // Success toast
                        toaster.pop("success","User saved", "User '" + new_user.user.Login + "' successfully created");
                        return data;
                },
                function(response) {
                    $log.debug("Failed to save user, error with status code", response.status);
                    toaster.pop("error", "Unable to save user", "Failed to save user, error with status code " + response.status);
                });
            }

        }
})(); 

On the first call to UserSrvc.getAllUsers() in the getUsers() function the data parameter from the .then(function(data) returns an array like so:

[
  {
    "Last": "Jobs",
    "Email": "[email protected]",
    "Login": "jobs",
    "id": 1,
    "First": "Steve"
  }
]

However, subsequent calls made by refreshUserTable() to the same UserSrvc.getAllUsers(), the data parameter from .then(function(data)) returns an object like so:

{
  "data":     [
      {
        "Last": "Jobs",
        "Email": "[email protected]",
        "Login": "jobs",
        "id": 1,
        "First": "Steve"
      }
    ]
}

To get it to work I need to pull the data array from the data object by doing data.data.

Why is it that subsequent calls made by the refreshUserTable() return an object and not an array? My suspicion is that it has something to do with the way in which I'm using Restangular or is there something glaringly obvious I've missed?

Ideally I'd like to get rid of the refreshUserTable() function and just use the getAllUsers() to refresh the table.

2
  • setFullResponse seems to set this flag for all subsequent requests. Does removing that change anything with the getAllUsers calls? Commented Mar 27, 2015 at 15:07
  • Awesome. Removing the setFulResponse fixed the problem (I only used it for debugging previously). Commented Mar 27, 2015 at 16:20

1 Answer 1

1

you set setFullResponse to true which extend your response object. You confused because Restangular uses same property key with you data.

If you want to use full response specifically on one method just use withConfig method of Restangular.

Restangular.withConfig(function(RestangularConfigurer) {
    RestangularConfigurer.setFullResponse(true);
});
Sign up to request clarification or add additional context in comments.

3 Comments

Ahhh, I didn't realise that would affect all Restangular requests! I've removed it and it works. Thanks! Should I be creating a Restangular "instance" for each function in my UserSrvc and not the way I'm currently doing it where I do 'Restangular.one' or 'Restangular.getList' etc.?
Should I be creating a Restangular "instance" for each function in my UserSrvc and not the way I'm currently doing it where I do 'Restangular.one' or 'Restangular.getList' etc.?
you can use it with different instances or use current instance withConfig method for specific rest call...

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.