0

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);
      })
    }
  }
YetAnotherBot
  • 1,937
  • 2
  • 25
  • 32

1 Answers1

0

Your factory/Service search method 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);
    })
  }
});
ram1993
  • 979
  • 1
  • 9
  • 13
  • You say "Your factory/Service not returning anything."... Why is it not returning anything? Is it not returning the entire Search method, indicated after the word 'return' in the { } block? –  Oct 01 '16 at 19:06
  • Sorry, I mean to say thingyFactory.search mehod. My bad. – ram1993 Oct 01 '16 at 19:43