DaveC426913 DaveC426913 - 5 months ago 22
AngularJS Question

angular promises and service

I just can't get my head around promises.
Conceptually I get what they're doing I just don't know how to write it (or, at least, debug it).

MyController.js

(function() {
angular.module('WizmoApp').controller('StoreController', storeController);
storeController.$inject = ['$scope', '$http', '$q', '$window', 'MyService', 'toastr'];
function storeController($scope, $http, $q, $window, MyService, toastr) {

StoreService.getStores().then(
function(response) {
console.log(response);
},
function(response) {
toastr.error(response);
});
}
})();


As far as I can tell, that is the format for a promise.

MyService.js

(function() {
angular
.module('WizmoApp')
.service('StoreService', storeService);
storeService.$inject = ['$http', '$q', 'ngAuthSettings'];

function storeService($http, $q, ngAuthSettings) {

this.getStores = function() {
$.getJSON('Content/data/Stores.json', function (json) {
return json;
});
};
})();


The error I get is


StoreService.getStores(...).then is not a function

Answer

You need to return the promise resolver so that you can invoke the .then() function on it. For example:

this.getStores = function() {
  return $q(function(resolve, reject) {
    $.getJSON('Content/data/Stores.json', function (json) {
        resolve(json);
    });
  });
}

Or the older CommonJS notation:

this.getStores = function() {
  var deferred = $q.defer();
  $.getJSON('Content/data/Stores.json', function (json) {
      deferred.resolve(json);
  });
  return deferred.promise;
}

Remember to inject $q into your StoreService. See here for more info: https://docs.angularjs.org/api/ng/service/$q