Tyler Tyler - 2 months ago 12
AngularJS Question

How to use promises between angular factories and controllers? - Having annoying issue - Thanks

Factory:

function thingyFactoryFunction($http) {
return {
search: function(city, state) {
$http({
method: 'POST',
url: 'http://localhost:7500/search',
data: {city: city, state: state}
}).then(function successCallback(res) {
return res
})
}
}
}


Here is my controller. I want the controller to simply grab the response from the factory above, and so I can set vm.thing to equal the promise response. However, I keep getting the error that if I see one more time I'm going to go berzerk: 'TypeError: Cannot read property 'then' of undefined'.

function thingyIndexControllerFunction(thingyFactory) {
var vm = this;
vm.city;
vm.state;
vm.search = function() {
thingyFactory.search(vm.city, vm.state).then(function(res) {
console.log(res);
})
}
}

Answer

Your factory/Service not returning anything. Your trying to access .then() of nothing(undefined). $http itself returns a promise object. Try following.

app.factory('thingyFactory', function($http) {
  return {
    search: function(city, state) {
      //This will return promise object.
      return $http({
        method: 'POST',
        url: 'http://localhost:7500/search',
        data: {
          city: city,
          state: state
        }
      });
    }
  }
});

in controller,

app.controller('thingyIndexController', function($scope, thingyFactory) {
  var vm = this;
  vm.search = function() {
    var promise = thingyFactory.search(vm.city, vm.state);
    //after promise resolved then() method get called
    promise.then(function(res) {
      console.log(res);
    })
  }
});