How to return a resolved promise from an AngularJS Service using $q?
From your service method:
function serviceMethod() {
return $timeout(function() {
return {
property: 'value'
};
}, 1000);
}
And in your controller:
serviceName
.serviceMethod()
.then(function(data){
//handle the success condition here
var x = data.property
});
Return your promise , return deferred.promise.
It is the promise API that has the 'then' method.
https://docs.angularjs.org/api/ng/service/$q
Calling resolve does not return a promise it only signals the promise that the promise is resolved so it can execute the 'then' logic.
Basic pattern as follows, rinse and repeat
http://plnkr.co/edit/fJmmEP5xOrEMfLvLWy1h?p=preview
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js@*" data-semver="1.3.0-beta.5"
src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-controller="test">
<button ng-click="test()">test</button>
</div>
<script>
var app = angular.module("app",[]);
app.controller("test",function($scope,$q){
$scope.$test = function(){
var deferred = $q.defer();
deferred.resolve("Hi");
return deferred.promise;
};
$scope.test=function(){
$scope.$test()
.then(function(data){
console.log(data);
});
}
});
angular.bootstrap(document,["app"]);
</script>
How to simply return a pre-resolved promise in AngularJS
Resolved promise:
return $q.when( someValue ); // angularjs 1.2+
return $q.resolve( someValue ); // angularjs 1.4+, alias to `when` to match ES6
Rejected promise:
return $q.reject( someValue );