0

我有这项服务可以从 WebAPI 服务器检索汽车列表:

    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的 cal 之后是未定义的。我在调用服务时尝试使用“then”,但没有成功。

说我想在服务本身处理操作的成功和错误,我怎样才能在控制器中获得最终结果?

4

1 回答 1

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;

        }
    }]
    );

现在“then”在控制器中工作:

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, '');
});
于 2016-08-26T02:25:52.110 回答