异步调用如何在AngularJS 1.X中工作? $ Http调用没有返回值 [英] How does asynchronous call work in AngularJS 1.X? $Http call not returning value
问题描述
我有以下函数名为 getvalue
。它与控制器一起位于AngularJS模块内。我试图在click事件中调用此函数调用控制器中的另一个函数。(我希望我很清楚)
I have the following function named getvalue
. It is inside an AngularJS module together with a controller. I am trying to call this function on click event invoking another function in a controller.(I hope I am clear)
功能:
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;
}
控制器内的代码
value= getvalue(formData, $http );
alert(value);//undefined here. Seems like value is never changed.
我没有获得警报值但是控制台正在打印该值。如果可能,我需要帮助两个问题。
I have not getting the value on alert but console is printing the value. I need help if possible for two issues.
- 如何从内部成功更改值并返回控制器?
- 有没有什么方法可以让我从控制器注入$ Http功能?
-----它会如果我可以为单元测试做到这一点,那就太好了。
推荐答案
你理想的想要拉$ http服务从控制器出来并让工厂做这些调用。
you would ideally want to pull the $http service out of the controller and make a factory to do those calls.
在工厂有一个函数,接受你想要发送的数据并拥有它将承诺退还给控制器
in the factory have a function that accepts the data you are wanting to send and have it return the promise back to the controller
类似这样的事情
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 some work
deferred.resolve(results);
})
.error(function(error){
// do some work
deferred.reject(error);
});
return deferred.promise;
}
}
}]);
这里是控制器
app.controller("fooCtrl", ["foo", function(foo){
foo.getValue(dataHere)
.then(function(results){
// do something here
});
}]);
这篇关于异步调用如何在AngularJS 1.X中工作? $ Http调用没有返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!