2016-08-26 3 views
0

나는 WebAPI 서버에서 자동차의 목록을 검색하려면이 서비스가 :AngularJS와는 : 컨트롤러에 서비스에서 객체의 목록을

angular.module('MyServices') 
    .service('carService', ['$http', '$rootScope', 
     function ($http, $rootScope) { 

     this.getList =function(userName, ticket) 
     { 
      $rootScope.$emit('My.OnBusy'); 

      $http.get('api/car' 
       , { params: {userName: userName} } 
      ).success(function (data) { 
       $rootScope.$emit('My.OnIdle'); 

       if (data[0] && data[0].Name == "Error") 
       { 
        $rootScope.$emit("My.OnError", data[0].Model); 
        return {}; 
       } 

       return data; 
      }).error(function (data, status, headers, config) { 
       $rootScope.$emit('My.OnIdle'); 
       $rootScope.$emit("My.OnError", "Error in communication with server."); 
       return {}; 
      }); 
     } 
    }] 
    ); 

그리고 나는이처럼 사용 컨트롤러 :

angular.module('MyControllers') 
.controller('carController', function CarController($rootScope, $scope, $http, carService) { 

    $scope.loadCars = function (userName, ticket) { 
     $scope.Cars = carService.getList(userName, ticket); 
    } 

    $scope.loadCars($rootScope.user.email, ''); 
}); 

그러나 $ scope.Cars에 칼 getList 후 정의되지 않습니다. 서비스를 호출했지만 성공하지 못했을 때 "then"을 사용하려고했습니다.

서비스 자체에서 성공과 오류를 처리하고 싶다면 컨트롤러에서 최종 결과를 얻으려면 어떻게해야합니까?

서비스는 다음과 같이해야한다 : 나중에 참조 할 수 있도록

답변

0

angular.module('MyServices') 
    .service('carService', ['$http', '$rootScope', '$q' 
     function ($http, $rootScope, $q) { 

     this.getList =function(userName, ticket) 
     { 
      $rootScope.$emit('My.OnBusy'); 

      var deferred = $q.defer(); 


      $http.get('api/car' 
       , { params: {userName: userName} } 
      ).success(function (data) { 
       $rootScope.$emit('My.OnIdle'); 

       if (data[0] && data[0].Name == "Error") 
       { 
        $rootScope.$emit("My.OnError", data[0].Model); 
        deferred.reject(data[0].Address); 
        //return {}; 
       } 

       deferred.resolve(data); 
       //return data; 
      }).error(function (data, status, headers, config) { 
       $rootScope.$emit('My.OnIdle'); 
       $rootScope.$emit("My.OnError", "Error in communication with server."); 
       deferred.reject("Error in communication with server.");     
       //return {}; 
      }); 

      return deferred.promise; 

     } 
    }] 
    ); 

이제 컨트롤러의 "다음" 작품 :

angular.module('MyControllers') 
.controller('carController', function CarController($rootScope, $scope, $http, carService) { 

    $scope.loadCars = function (userName, ticket) { 
     carService.getList(userName, ticket).then(function (data) { 
      $scope.Cars = data; 
     });; 
    } 

    $scope.loadCars($rootScope.user.email, ''); 
});