2016-08-26 36 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的CAL到的GetList後是不確定的。我試圖在撥打服務時使用「然後」,但它不成功。

說,我要處理的服務本身運行的成功和錯誤,我怎樣才能得到最終的結果在控制器?

回答

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, ''); 
}); 
相關問題