如何在Angular中为控制器获取ajax结果?

时间:2015-12-11 10:01:51

标签: javascript angularjs

我有一个服务从我的ajax调用中获取值。我想将该值存储在变量中并将该变量传递给控制器​​。

angular.module("Data", []).service("DataService", function($http) {
  return {
    Data: function(callback) {
      $http.get('http://www.w3schools.com/angular/customers.php').success(callback);
    }
  }
})

angular.module("Home", ["Data"]).service("HomeService", function(DataService) {
  var customerData = {}
  return {
    Getdata: DataService.getCustomers(function(results) {
      customerData = results;
      console.log(customerData)
    })
  }
})


angular.module("Home").controller("HomeCntrl", function($scope, HomeService) {

  $scope.Result = HomeService.Getdata;

})

我希望数据存储在customerData中,我必须将customerData传递给控制器​​。

2 个答案:

答案 0 :(得分:2)

你不应该为此使用回调(虽然它也可以),不是很方便。 Promises就是这种情况的一切。所以你的代码应该是这样的:

angular.module("Data", []).service("DataService", function($http) {
    return {
        getCustomers: function() {
            return $http.get('http://www.w3schools.com/angular/customers.php').then(function(response) {
                return response.data;
            });
        }
    }
});

angular.module("Home", ["Data"]).service("HomeService", function(DataService) {
    return {
        getData: function() {
            return DataService.getCustomers().then(function(data) {
                console.log('customers', data);
                // maybe process data further and return new set
                return data;
            });
        }
    }
});

angular.module("Home").controller("HomeCntrl", function($scope, HomeService) {
    HomeService.getData().then(function(data) {
        $scope.Result = data;
    });
});

演示: http://plnkr.co/edit/7V2mqacof72Ad9cuCivh?p=preview

答案 1 :(得分:0)

请看我的例子:

https://github.com/AlexRepeckiy/todolist/tree/master/app

关注服务和控制器文件夹。

小例子:

app.controller('MainCtrl', ['$scope', 'DataService', function($scope, DataService) {


    DataService.getData().then(function (results) {
        $scope.tasks = results;
    }); 

}]);

app.factory('DataService', ['$http', '$q', function ($http, $q) {
var exports = {};

exports.getData = function () {
    var deferred = $q.defer();

    $http.get('/gettask')
        .then(
            function (result) {
                deferred.resolve(result.data);
            },
            function (error) {
                deferred.reject(error);
                console.log('Getting is fail :' + error);
        });

    return deferred.promise;
 };

   return exports;
}]);

没有延期:

app.factory('DataService', ['$http', function ($http) {
var exports = {};

exports.getData = function () {


    return $http.get('/gettask')
        .then(
            function (result) {
                return result.data;
            },
            function (error) {

                console.log('Getting is fail :' + error);
        });
 };

   return exports;
}]);