【发布时间】:2016-08-26 01:35:55
【问题描述】:
我有这项服务可以从 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 之后是未定义的。我在调用服务时尝试使用 "then",但未成功。
说我想在服务本身处理操作的成功和错误,我如何在控制器中获得最终结果?
【问题讨论】:
标签: angularjs asp.net-web-api get promise deferred-loading