我无法在我的代码中找到错误,但$ q.defer()。reject()似乎无法正常工作。 defer.resolve工作得很好,甚至可以进入finally段,但是defer.reject(虽然不会抛出任何错误但是)不会返回then函数,也不会返回finally函数 我正在使用angularjs版本1.5.8
// calling service
DashboardFactory.getDashboard($scope.dashboardData.dsDetails.dashName).then(
function (response) {
debugger;
console.log('success');
},
function () {
console.log('reject');
}
).finally(function() {
debugger;
console.log('finally');
});
// service
var defer = $q.defer();
$timeout(function() {
$http(httpParams)
.success(function(data, status, headers, config) {
defer.resolve(data);
})
.error(function(error, status, headers, config) {
console.log('error');
defer.reject('error');
})
}, 0);
return defer.promise;
答案 0 :(得分:0)
$q
是一项服务,允许您以异步方式运行函数,并且可以使用promises。
但$http
服务方法get post put ...
已经返回承诺,因此您不需要它,但如果您真的坚持使用它,您可以像这样使用它:
<!DOCTYPE html>
<html>
<head>
<script data-require="angularjs@1.5.8" data-semver="1.5.8" src="https://opensource.keycdn.com/angularjs/1.5.8/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script>
var app = angular.module('yourApp', []);
app.service('YourService', function($http, $q) {
var url = "https://jsonplaceholder.typicode.com/users/";
this.getUserWithQ = function(id) {
var deferred = $q.defer();
$http.get(url+id).then(
function(data) {
deferred.resolve(data);
},
function(error) {
deferred.reject(error);
}
);
return deferred.promise;
};
this.getUserWithoutQ = function(id) {
return $http.get(url+id);
}
})
app.controller('YourCtrl', function($scope, YourService) {
YourService.getUserWithQ(1).then(
function(res) {
$scope.userWithQ = res.data;
},
function(error) {
//unused
}
);
YourService.getUserWithQ(11).then(
function(res) {
//unused
},
function(error) {
$scope.userWithQerror = error;
}
);
//Just for the record
YourService.getUserWithoutQ(1).then(
function(res) {
$scope.userWithoutQ = res.data;
},
function(error) {
//unused
}
);
YourService.getUserWithoutQ(11).then(
function(res) {
//unused
},
function(error) {
$scope.userWithoutQerror = error;
}
);
});
</script>
</head>
<body ng-app="yourApp">
<div ng-controller="YourCtrl">
<div>
<div>
With $q success:
{{userWithQ}}
</div>
<br>
<div>
With $q error:
{{userWithQerror}}
</div>
</div>
<br>
<div>
<div>
Without $q success:
{{userWithoutQ}}
</div>
<br>
<div>
With $q error :
{{userWithQerror}}
</div>
</div>
</div>
</body>
</html>
我已将此api用作具有10个用户的示例https://jsonplaceholder.typicode.com/users/
,并且11将产生错误。
如您所见,您可以使用$q.defer()
和$http
返回值获得相同的结果。
以下是plunker