javascript - AngularJS $http.post inside function -
i using angularjs , inside service have this:
var fn = {     test: function() {         $http.post(...)         .success(function(response) {             console.log(response);             return response;         })     } }  this.testpostcall = function (id) {    console.log(fn.test()); }; in controller testpostcall undefined, in fact in console first output undefined , second 1 correct json response.
do know why undefined inside controller ?
this because doing asynchronous procedure not synchronous one. indicated in $http documentation:
the $http api based on deferred/promise apis exposed $q service
your code showing correct behaviour, because fn.test() function not return , therefore evaluates undefined. if want access data received test function, have return $http.post() itself.
it should this:
var fn = {     test: function() {         return $http.post(...);     } };  fn.test().success(function(data) {   console.log(data); }); 
Comments
Post a Comment