lilbiscuit
lilbiscuit

Reputation: 2249

Angular $http called from service, 'then' is undefined

I have seen this question many times but I can't figure out why one of my controller functions (controller 1) works fine and one (controller 2) doesn't.

Controller 1:

angular.module('app').controller('MyCtrl1',function($scope,MyFactory)) {

  //This function works great
  MyFactory.deleteItem(item.id).then(function(response) {
    //woot woot I am here and I am fine
  });
}); //end controller 1

Controller 2:

angular.module('app').controller('MyCtrl2',function($scope,MyFactory)) {

 //Function #2 that doesn't work ... 'then' is undefined
  MyFactory.createItem(item).then(function(response) {
    //booo hooo I never get here and I am definitely not fine
  });
}); //end controller 2

The factory:

.factory("MyFactory", function($http) {

var service = [];

service.deleteItem = function(itemId) {
  return $http({
    method: "delete",
    url: "http://www.example.com",
    params: //valid params go here
  }).then(function(response) {
    console.log("DELETING!!!!");
    return response.data;
  });
}

service.createItem = function(post) {
  return $http({
      url: '?create',
      method: 'post',
      headers: {'Content-Type': 'application/x-www-form-urlencoded'},
      data: payload //an object
    }).then(function(response){      
      console.log(response.data); //we are fine here. there is a valid response 
      return response.data; 
   });
}
return service;
}); //end factory

The error thrown when executing 'createItem' is 'Cannot read property 'then' of undefined' What am I missing ?

Upvotes: 0

Views: 93

Answers (2)

ojus kulkarni
ojus kulkarni

Reputation: 1907

If you are not returning $http the use like this :

$http({
  url: '?create',
  method: 'post',
  headers: {'Content-Type': 'application/x-www-form-urlencoded'},
  data: payload //an object
}).$promise.then(function(response){      
  console.log(response.data); 
  return response.data; 
});

Upvotes: -2

Omri Aharon
Omri Aharon

Reputation: 17064

You are missing the return in the createItem statement:

service.createItem = function(post) {
   return $http({
      url: '?create',
      method: 'post',
      headers: {'Content-Type': 'application/x-www-form-urlencoded'},
      data: payload //an object
    }).then(function(response){      
      console.log(response.data); //we are fine here. there is a valid response 
      return response.data; 
   });
}

Without it, there is no return value (which is undefined) on which you can't chain the .then.

Upvotes: 3

Related Questions