最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to call ajax from service in AngularJS? - Stack Overflow

programmeradmin3浏览0评论

I have Employee controller which is having property Id, Name , Specification. I have made one Employee service which is having ajax call and get employee list. But every time getting '' in User. When i debug the code i found that it call success first and then it goes for Ajax call. When i do ajax call without service it works fine.

 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 pletes
        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 pletes
        return true;
    };

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

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

}]);

I have Employee controller which is having property Id, Name , Specification. I have made one Employee service which is having ajax call and get employee list. But every time getting '' in User. When i debug the code i found that it call success first and then it goes for Ajax call. When i do ajax call without service it works fine.

 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 pletes
        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 pletes
        return true;
    };

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

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

}]);
Share Improve this question edited Oct 2, 2016 at 9:31 cbass 2,5583 gold badges29 silver badges39 bronze badges asked Nov 4, 2014 at 11:24 Hemant MalpoteHemant Malpote 89114 silver badges30 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

It's because you are returning the users before the data is fetched from the server. Also it doesn't seem like you are assigning them correctly.

Here are two ways to solve the problem:

Firstly. You bind your controller user-data to the user-data in the service.

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

And the second way would be to return the promise in the service and unwrap it in the controller.

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.";
       };

}]);

OFF TOPIC You should probably consider using ngModel instead of jQuery to get you data to the controller. Not like this:

var empData = {
      Id: $("#txtId").val(),
      Name: $("#txtName").val(),
      Expertise: $("#expertise").val()
};
// 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
发布评论

评论列表(0)

  1. 暂无评论