data.data for reading my json

时间:2015-10-30 23:03:08

标签: json angularjs angular-promise angularjs-factory angularjs-http

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?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

You can try something like this:

'use strict';

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

Then keep the other function as:

'use strict';

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

        }
    );
});

What happens is that the first promise return is chained with the second then(..) but the second one gets the extracted data. It's a cool thing about promises.