2014-11-04 1 views
2

속성 ID, 이름, 사양을 가진 직원 컨트롤러가 있습니다. 저는 아약스 전화를 받고 직원 목록을 얻는 직원 서비스를 하나 만들었습니다. 하지만 매번 ''사용자가되고 있습니다. 내가 코드를 디버깅 할 때 먼저 성공을 호출 한 다음 Ajax 호출을 찾는다. 서비스없이 AJAX 호출을하면 제대로 작동합니다.AngularJS에서 서비스 아약스 전화하는 방법?

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

}]); 

답변

4

데이터가 서버에서 가져온되기 전에 사용자를 반환하는 때문입니다. 또한 올바르게 할당하는 것처럼 보이지 않습니다.

다음은 문제를 해결하는 두 가지 방법입니다.

먼저. 컨트롤러 사용자 데이터를 서비스의 사용자 데이터에 바인딩합니다.

두 번째 방법은 서비스에서 약속을 반환하고 컨트롤러에서 언랩하는 것입니다.

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 주제 당신은 아마 당신이 컨트롤러에 데이터를 가져 오는 대신에 jQuery를의 ngModel을 사용하는 것이 좋습니다. 싫어함 :

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

감사 ... 두 번째 작품이 여기 있습니다. –

+0

예 두 번째 작품입니다. – rahul

+0

헤더 : { 'Content-Type': 'application/x-www-form-urlencoded'}는 데이터와 함께 작동합니다. $ ('# formid'). serialize() – Zerubbabel

0
// 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