javascript - How does asynchronous call work in AngularJS 1.X? $Http call not returning value -
i have following function named getvalue
. inside angularjs module controller. trying call function on click event invoking function in controller.(i hope clear)
function:
function getvalue(data, $http) { var value=undefined; $http({ url: /myurl, method: "get", params: { tmp: data.tmp, pressure: data.pressure } }).success(function (data, status, headers, config) { value=parsefloat( console.log(data));//console working here return value; }); return value; }
code inside controller
value= getvalue(formdata, $http ); alert(value);//undefined here. seems value never changed.
i have not getting value on alert console printing value. need if possible 2 issues.
- how can change value inside success , return controller?
- is there way don't have inject $http controller function? -----it nice if can unit testing.
you ideally want pull $http service out of controller , make factory calls.
in factory have function accepts data wanting send , have return promise controller
something this
repo
app.factory("foorepo", ["$http", function($http){ return { getvalue: function(data){ return $http({ method: "post", url: "/myurl" }); } }; }]);
serivce
app.factory("foo", ["$q", "foorepo", function($q, foorepo){ return { getvalue: function(data){ var deferred = $q.defer(); foorepo.getvalue(data) .success(function(results){ //do work deferred.resolve(results); }) .error(function(error){ // work deferred.reject(error); }); return deferred.promise; } } }]);
here controller
app.controller("fooctrl", ["foo", function(foo){ foo.getvalue(datahere) .then(function(results){ // here }); }]);
Comments
Post a Comment