AngularJS : returning data from service to controller

后端 未结 2 1607
悲&欢浪女
悲&欢浪女 2020-12-30 12:57

I am trying to create a service to get json and pass it to me homeCtrl I can get the data but when a pass it to my homeCtrl it always returns undefined. Im stuck.

M

2条回答
  •  悲哀的现实
    2020-12-30 13:39

    You should return promise from getResponders function, & when it gets resolved it should return response.data from that function.

    Factory

    var myService = angular.module("xo").factory("myService", ['$http', function($http) {
        return {
            getResponders: function() {    
                return $http.get('myUrl')
                .then(function(response) {
                    console.log("coming from servicejs", response.data);
                    //return data when promise resolved
                    //that would help you to continue promise chain.
                    return response.data;
                });
            }
        };
    }]);
    

    Also inside your controller you should call the factory function and use .then function to get call it when the getResponders service function resolves the $http.get call and assign the data to $scope.gotData

    Code

     $scope.goData = function(){
         myService.getResponders.then(function(data){
              $scope.gotData = data;
         });
    
     };
    

提交回复
热议问题