【问题标题】:How to call ajax from service in AngularJS?如何从AngularJS中的服务调用ajax?
【发布时间】:2014-12-31 06:32:07
【问题描述】:

我有 Employee 控制器,它具有属性 Id、Name 和 Specification。我已经做了一项员工服务,该服务正在进行 ajax 调用并获取员工名单。但每次在用户中获取''。 当我调试代码时,我发现它先调用成功,然后再调用 Ajax。 当我在没有服务的情况下进行 ajax 调用时,它工作正常。

 angular.module('EmployeeServiceModule', [])
.service('EmployeeSer', ['$http',function ($http) {
    this.Users = '';
    this.errors = '';
    this.SearchEmployee = function () {
 // Ajax call
        $http({
            method: 'GET',
            url: '/Home/GetEmployeeList',
            params: { filterData: 'Test' },
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).then(onSuccess, onError);

        var onSuccess = function (response) {
            this.userUsers = response.data;
            this.errors = '';
        };

        var onError = function (reason) {
            this.userUsers = reason;
            this.errors = "Error in retrieving data.";
        };

        return this.Users;
    }   
}]);


angular.module('Employee', ['EmployeeServiceModule'])
.controller('EmployeeController', ['EmployeeSer', '$scope', '$http', function (EmployeeSer, $scope, $http) {

    this.Id = '';
    this.name = '';
    this.expertise = '';
    $scope.repoSortOrder = 'id';
    $scope.filterField = '';

    // Call to service
    this.GetAllEmployee = function () {
        // Initiates the AJAX call
        $scope.User = EmployeeSer.SearchEmployee();
        // Returns the promise - Contains result once request completes
        return true;
    };

    this.AddEmployee = function () {
        var empData = {
            Id: $("#txtId").val(),
            Name: $("#txtName").val(),
            Expertise: $("#expertise").val()
        };

        $http({
            method: 'POST',
            url: '/Home/Create',
            params: JSON.stringify(empData),
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).then(onSuccess, onError);
        // Returns the promise - Contains result once request completes
        return true;
    };

    var onSuccess = function (response) {
        $scope.user = response.data;
        $scope.error = '';
    };

    var onError = function (reason) {
        $scope.error = "Error in retrieving data.";
    };

}]);

【问题讨论】:

    标签: javascript angularjs ajax promise angular-promise


    【解决方案1】:
    // Here serverRequest is my service to make requests to the server
    
    serverRequest.postReq = function(url, data, sucessCallback, errorCallback){
    $http({
    method: 'POST', 
    url: urlToBeUsed, 
    data:data,
    headers : {'Content-Type': 'application/x-www-form-urlencoded'}})
    .success(function(data, status, headers, config) {
    sucessCallback(data);
    })
    .error(function(data, status, headers, config){
    errorCallback(data);
    })
    }
    
    // In the controller 
    serverRequest.postReq('urlToBeCalled', dataToBeSent, scope.successCb, scope.errorCb);
    
    scope.successCb = function(data){
    // functionality to be done
    }
    scope.errorCb = function(data){
    // functionality to be done
    }
    
    Try it this way your problem might be solved
    Promise must be unwrapped in your controller if you want to use it
    

    【讨论】:

      【解决方案2】:

      这是因为您在从服务器获取数据之前返回用户。此外,您似乎没有正确分配它们。

      这里有两种解决问题的方法:

      首先。您将控制器用户数据绑定到服务中的用户数据。

      angular.module('EmployeeServiceModule', [])
            .service('EmployeeSer', ['$http',function ($http) {
                this.Users = '';
                this.errors = '';
                $http({
                   method: 'GET',
                   url: '/Home/GetEmployeeList',
                   params: { filterData: 'Test' },
                   headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
                }).then(onSuccess, onError);
      
                var onSuccess = function (response) {
                    this.Users = response.data;
                    this.errors = '';
                };
      
               var onError = function (reason) {
                    this.users = null;
                    this.errors = "Error in retrieving data.";
               };
           }   
      }]);
      
      
      angular.module('Employee', ['EmployeeServiceModule'])
             .controller('EmployeeController', ['EmployeeSer', '$scope', '$http', function (EmployeeSer, $scope, $http) {
                 this.users = EmployeeSer.users;
                 EmployeeSer.SearchEmployee();
      }]);
      

      第二种方法是在服务中返回承诺并在控制器中解包。

      angular.module('EmployeeServiceModule', [])
             .service('EmployeeSer', ['$http',function ($http) {
                this.SearchEmployee = function () {
                     return $http({
                        method: 'GET',
                        url: '/Home/GetEmployeeList',
                        params: { filterData: 'Test' },
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
                     });
                }   
      }]);
      
      
      angular.module('Employee', ['EmployeeServiceModule'])
             .controller('EmployeeController', ['EmployeeSer', '$scope', '$http', function (EmployeeSer, $scope, $http) {
      
             this.GetAllEmployee = function () {
                  EmployeeSer.SearchEmployee()
                             .then(onSuccess, onError)
             };
      
             var onSuccess = function (response) {
                  $scope.user = response.data;
                  $scope.error = '';
             };
      
             var onError = function (reason) {
                  $scope.error = "Error in retrieving data.";
             };
      
      }]);
      

      题外话 您可能应该考虑使用 ngModel 而不是 jQuery 将数据发送到控制器。 不是这样的:

      var empData = {
            Id: $("#txtId").val(),
            Name: $("#txtName").val(),
            Expertise: $("#expertise").val()
      };
      

      【讨论】:

      • headers: { 'Content-Type': 'application/x-www-form-urlencoded' } 使用数据:$('#formid').serialize()
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-20
      • 2016-09-13
      • 2017-02-07
      • 1970-01-01
      • 2014-06-27
      • 2017-12-08
      • 2013-04-11
      相关资源
      最近更新 更多