Search code examples
jsonangularjsangular-promiseangularjs-factoryangularjs-http

data.data for reading my json


I have this factory:

'use strict';

angular.module('testCon').factory('UserService', function ($http) {
   return {
       getAll: function () {
           return $http.get('http://localhost:1337/api/user');
       }
   }
});

And this controller:

'use strict';

angular.module('testCon').controller('UserController', function ($scope, UserService) {
    $scope.users = [];
    UserService.getAll().then(
        function (data) {
            $scope.users = data.data;
        }, function (err) {

        }
    );
});

Can I somehow avoid the data.data I would like to have only data. What is it that forces me to do data.data in order to see it in the scope?


Solution

  • Simply you can't avoid that. You could make that as one time change by returning only a response.data from getAll method. Then all the consumer will get direct data.

    Code

    angular.module('testCon').factory('UserService', function ($http) {
       return {
           getAll: function () {
               return $http.get('http://localhost:1337/api/user').then(function(response){
                    return response.data
               });
           }
       }
    });