Angular JS promise in custom service function that not using http
https://appendto.com/2016/02/working-promises-angularjs-services/
(function() {
'use strict';
angular
.module('testApp')
.service('testService', testService)
.controller('testCtrl', testCtrl)
.controller('testCtrl2', testCtrl2);
function testService($http, $q) {
// will hold backend posts
var posts = undefined;
// fetch all posts in deferred technique
this.getPosts = function() {
// if posts object is not defined then start the new process for fetch it
if (!posts) {
// create deferred object using $q
var deferred = $q.defer();
// get posts form backend
$http.get('https://jsonplaceholder.typicode.com/posts')
.then(function(result) {
// save fetched posts to the local variable
posts = result.data;
// resolve the deferred
deferred.resolve(posts);
}, function(error) {
posts = error;
deferred.reject(error);
});
// set the posts object to be a promise until result comeback
posts = deferred.promise;
}
// in any way wrap the posts object with $q.when which means:
// local posts object could be:
// a promise
// a real posts data
// both cases will be handled as promise because $q.when on real data will resolve it immediately
return $q.when(posts);
};
}
function testCtrl($scope, testService) {
$scope.getPosts = function() {
testService.getPosts()
.then(function(posts) {
console.log(posts);
});
};
$scope.getPosts();
}
function testCtrl2($scope, testService) {
$scope.getPosts = function() {
testService.getPosts()
.then(function(posts) {
console.log(posts);
});
};
$scope.getPosts();
}
})();