Reputation: 18328
I'm in a spot where I need to return a promise, that would otherwise be returned by a server http request, and I need it to be rejected, so I don't needlessly hit the server. I've been trying to make and return a rejected promise, something like:
var promise = $q.defer().promise;
return promise.reject( value ); // doesn't work
or
return $q.reject(); // also doesn't work
I can't seem to figure out how to return a rejected promise so I can save the server call, but I'm in a spot where it is either return a made-up rejected promise or make the server call. I'm in between both where I'm not in the original child directive that invoked the call, and the child wasn't able to make the comparison that was possible in the parent directive. Is there anyway to do this without a $timeout?
Upvotes: 0
Views: 221
Reputation: 388436
I think what you are looking for is
var app = angular.module('my-app', [], function() {
})
app.controller('AppController', ['$scope', '$q',
function($scope, $q) {
$scope.message = 'This is for testing';
function test() {
//create a deferred object
var deferred = $q.defer();
//reject the promise
deferred.reject(2);
//then return the promise
return deferred.promise;
}
test().then(function() {
$scope.message = 'Resolved';
}, function() {
$scope.message = 'Rejected';
})
}
])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="my-app" ng-controller="AppController">
{{message}}
</div>
The deffered api has the reject/resolve method, where as the promise api has methods used to register the callback methods
Upvotes: 2