异步调用如何在AngularJS 1.X中工作? $ Http调用没有返回值

时间:2015-07-21 19:52:23

标签: javascript angularjs http asynchronous

我有以下名为getvalue的函数。它与控制器一起位于AngularJS模块内。我试图在click事件中调用此函数来调用控制器中的另一个函数。(我希望我很清楚)

功能

  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.

我没有获得警报值,但控制台正在打印该值。如果可能,我需要帮助解决两个问题。

  1. 如何从内部成功更改值并返回控制器?
  2. 有没有办法让我从控制器注入$ Http功能? -----如果我能为单元测试做到这一点会很好。

4 个答案:

答案 0 :(得分:1)

当您调用正在执行异步调用的方法时,您必须从那里返回promise,因为您不知道数据何时从ajax返回。如果ajax成功,你应该更新你的变量。在ajax函数之外,您将获得未定义的值,因为值以异步方式返回。

<强>功能

 function getvalue(Data) {
      var value=undefined;
      return $http({
          url: /myurl,
          method: "GET",
          params: {
              tmp: Data.tmp,
              pressure: Data.pressure               
            }
      })
}

<强>控制器

 getvalue(formData).success(function (data, status, headers, config) {            
      console.log(data);//you will get data here
 });

答案 1 :(得分:1)

理想情况下,您希望将$ http服务从控制器中拉出来并建立工厂来进行这些调用。

工厂中的

有一个函数接受你想要发送的数据并让它将承诺返回给控制器

类似这样的事情

回购

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
        });
}]);

Added Plunkr

答案 2 :(得分:0)

$ http-Request是异步的。这意味着在执行.success(..)回调之前将调用alert。

您可以在控制台上看到结果,因为它反映了在调用console.log()之后所做的更改。

调用警报(值);在.success()中 - 回调将屏蔽所需的结果。

答案 3 :(得分:-2)

替换:

 }).success(function (data, status, headers, config) {            
     value=parseFloat(  console.log(data));//console working here
     return value;
});

使用:

 }).success(function (data, status, headers, config) {            
     alert(parseFloat(data));
});