$ http通过服务调用,然后将数据拉入Controller(AngularJS)

时间:2016-02-21 17:56:22

标签: angularjs json http service controller

修改

问题:想要通过服务致电userdata.json(数组),然后在我的控制器中调用,以便随后可以调用数据查看

目前的情况:

APP:

angular.module('UsersApp', []);

SERVICE:

angular.module('UsersApp').factory('UserService', function($http) {
    this.getUserData = function() {
        return $http.get('userdata.json');
    }
})

控制器:

angular.module('UsersApp').controller('UserController', [
        'UserService', // dependency on service
        '$mdSidenav', 
        '$mdBottomSheet', 
        '$log',
        '$timeout',
        UserController // calling a function (defined below)
        ]);


// Declare controller as a function, then attach properties using 'this'.
//-------------------------------------------------------------------------

function UserController( UserService, $mdSidenav, $mdBottomSheet, $log, $timeout ) {

        var self = this;

        self.selected     = null;
        self.users        = [];
        self.selectUser   = selectUser;
        self.toggleList   = toggleUsersList;
        self.makeContact  = makeContact;


// Fetch user data from UserService.js
//-------------------------------------------------------------------------


function(UserService) {

    var data = UserService.getData();

   };


// Internal methods
//-------------------------------------------------------------------------

    // Hide or Show the 'left' sideNav area

    function toggleUsersList() {
      $mdSidenav('left').toggle();
    }


    // Select the current avatars
    // @param menuId

    function selectUser ( user ) {
      self.selected = angular.isNumber(user) ? $scope.users[user] : user;
    }



// Show the bottom sheet
//------------------------------------------------------------------------------

    function makeContact(selectedUser) {

        $mdBottomSheet.show({

            controller     : [ '$mdBottomSheet', ContactSheetController],
            controllerAs : "vm",
            templateUrl    : './partials/contactSheet.html',
            parent         : angular.element(document.getElementById('content'))

            })

            .then(function(clickedItem) {
                $log.debug( clickedItem + ' clicked!');
            });


        // User ContactSheet controller
        //---------------------------------------------------------------------

        function ContactSheetController( $mdBottomSheet ) {

            this.user = selectedUser;

            this.items = [
                { name: 'Phone'       , icon: 'phone'       , icon_url: 'svg/phone.svg'},
                { name: 'Twitter'     , icon: 'twitter'     , icon_url: 'svg/twitter.svg'},
                { name: 'Google+'     , icon: 'google_plus' , icon_url: 'svg/google_plus.svg'},
                { name: 'Hangout'     , icon: 'hangouts'    , icon_url: 'svg/hangouts.svg'}
            ];

            this.contactUser = function(action) {
                // Fill in contact process here...
                // then finish up with...
                $mdBottomSheet.hide(action);
            };
        }
    }

  }

JSON DATA(数组):

[
      {
        'name': 'Lia Lugo',
        'avatar': 'svg-1',
        'content': 'I love cheese, especially airedale queso. Cheese and biscuits halloumi cauliflower cheese cottage cheese swiss boursin fondue caerphilly. Cow port-salut camembert de normandie macaroni cheese feta who moved my cheese babybel boursin. Red leicester roquefort boursin squirty cheese jarlsberg blue castello caerphilly chalk and cheese. Lancashire.'
      },
      {
        'name': 'George Duke',
        'avatar': 'svg-2',
        'content': 'Zombie ipsum reversus ab viral inferno, nam rick grimes malum cerebro. De carne lumbering animata corpora quaeritis. Summus brains sit​​, morbo vel maleficia? De apocalypsi gorger omero undead survivor dictum mauris.'
      },
      {
        'name': 'Gener Delosreyes',
        'avatar': 'svg-3',
        'content': "Raw denim pour-over readymade Etsy Pitchfork. Four dollar toast pickled locavore bitters McSweeney's blog. Try-hard art party Shoreditch selfies. Odd Future butcher VHS, disrupt pop-up Thundercats chillwave vinyl jean shorts taxidermy master cleanse letterpress Wes Anderson mustache Helvetica. Schlitz bicycle rights chillwave irony lumberhungry Kickstarter next level sriracha typewriter Intelligentsia, migas kogi heirloom tousled. Disrupt 3 wolf moon lomo four loko. Pug mlkshk fanny pack literally hoodie bespoke, put a bird on it Marfa messenger bag kogi VHS."
      }
];

不工作。如果有人能够发现什么是错误的 - 尝试过并尝试过但却无法解决问题,我将不胜感激。

4 个答案:

答案 0 :(得分:3)

angular.module('app').service('UserService', function($http) {
    this.getUserData = function() {
        return $http.get('userdata.json')
    }
})


angular.module('app').controller('MyController', function(UserService) {
    var self=this;
    UserService.getUserData().then(function(data) {
         self.userdata = data;
         console.log(self.userdata);
    }).catch(function(errorResponse) {
         console.log('oopsie', errorResponse);
    });
}

如果您使用控制器作为语法,那么效果很好,如果不使用$ scope.userdata = data

答案 1 :(得分:2)

您需要在服务中的承诺中返回数据,不要将其分配给范围。

然后在控制器中,您只需调用您的服务函数并将其结果分配给控制器中的范围变量。

答案 2 :(得分:1)

您可以先创建控制器,然后使用依赖注入添加服务,例如

angular.module("app").controller('controller_App',['userService',function(userService)
   {
  var data=  userService.getData();


   }]);

在服务中,你可以像这样使用$ http依赖

    angular.module("app").service("userService",['$http',function($http){


    $http({url:'https://www.any_link.com'}).then(function(successResponse){

    return successResponse;       

    },function(errorResponse){

     return errorResponse    
   });




    }

    }]);

答案 3 :(得分:1)

只需在您的服务方法中返回承诺:

angular.module('UserApp').service('UserService', ['$http', UserService]);

function UserService($http) {
    var self = this;
    self.getData = function () {
        return $http.get('userdata.json')
    };
};

将此服务注入控制器并使用它:

angular.module('UserApp').controller('UserController', ['$scope', 'UserService', UserController]);

function UserController($scope, UserService) {

    $scope.users = null;
    UserService.getData()
        .success(function(data) {
            $scope.users = data;
        })
};