Angularjs获取函数之外的对象值

时间:2015-07-20 10:10:19

标签: javascript angularjs

我需要在下面的函数中打印出localeData值。 我知道如何在功能方面打印,就像我在这里做的那样。 我试过这个但是没用。

    $http.post(SERVER_URL + 'getLocaleData').success(function(localeData) {
        console.log(localeData);
        }).error(function(err) {
            alert('warning', err.message);
        });
        //need to get that value here.
        console.log(localeData);

修改

其实我需要做的就是这个

app.factory('customLoader', function($http, $q, SERVER_URL) {

    return function(options) {
        var deferred = $q.defer();

        // do something with $http, $q and key to load localization files
        $http.post(SERVER_URL + 'getLocaleData').success(function(localeData) {
         //do something here to localData
        }).error(function(err) {
            alert('warning', err.message);
        });

        deferred.resolve(localeData);
        return deferred.promise;

    };
});

这就是我需要的。最后我需要发送localeData。

5 个答案:

答案 0 :(得分:1)

您无需创建&解决一个推迟自己。有一种更简单的方法。 (同样在您给出的示例中,您在基础ajax完成之前解决了承诺)

Angular.js $http服务也跟在$q界面之后!所以你可以写:

app.factory('customLoader', function($http, $q, SERVER_URL) {
  return function(options) {
    var promise = $http.post(SERVER_URL + 'getLocaleData')
      .then(function(localeDataBag) {
         var localeData = localeDataBag.data; // .data of 'then' equals to what .success returns.            
         modifiedLocaleData = localeData++;  // do something here to localData
         return modifiedLocaleData; // This is the new result
        })
      .catch(function(err) {
        console.log(err);
        return $q.reject(err); // This is the new result if something failed. Since we are chaining promises, we should keep failure state.
      });
    return promise;
  };
});

答案 1 :(得分:0)

JS是异步的,这基本上意味着您的服务器返回任何数据之前将执行您的上一个console.log。所以你必须在你的承诺中做到这一点:

$http.post(SERVER_URL + 'getLocaleData').success(function(localeData) {
    console.log(localeData);
    }).error(function(err) {
         console.log(err);
        alert('warning', err.message); //Just in case you didn't know, this line supposes that your server returns a JSON object with a "message"-property

    });

这样,您的服务器响应将在成功和失败时console.log

Reference

编辑:如果你真的想以另一种方式去做:

var response; //First, declare a variable in the parent scope.

$http.post(SERVER_URL + 'getLocaleData').success(function(localeData) {
    response = localeData; //Assign the response data to the variable.
    console.log(localeData);
    }).error(function(err) {
        alert('warning', err.message); //Just in case you didn't know, this line supposes that your server returns a JSON object with a "message"-property

    });
    console.log(response);

但是,该示例不会按预期进行评估。最后一个console.log只会记录undefined

答案 2 :(得分:0)

localeData仅限于.success函数的范围。除非你给它指定一些其他变量,否则你无法将它传到外面。

var data = ""
$http.post(SERVER_URL + 'getLocaleData').success(function(localeData) {
    data = localeData;
    }).error(function(err) {
        alert('warning', err.message);
    });
//need to get that value here.
console.log(data);

但是,在获得回复之前,不要期望在data中获得所需的值。 $http.post 异步

看看承诺来克服这些问题,因为它们在角落世界中被广泛使用。

<强>更新

正如您在编辑中所做的那样,您可以使用 $ q 服务,例如:

app.factory('customLoader', function($http, $q, SERVER_URL) {

    return function(options) {
        var deferred = $q.defer();

        // do something with $http, $q and key to load localization files
        $http.post(SERVER_URL + 'getLocaleData').success(function(localeData) {
         //do something here to localData
        }).error(function(err) {
            alert('warning', err.message);
        });

        deferred.resolve(localeData);
        return deferred.promise;

    };
});

或者,你可以简单地返回$http.post,它本身会返回一个承诺

app.factory('customLoader', function($http, $q, SERVER_URL) {
    return function(options) {        
        return $http.post(SERVER_URL + 'getLocaleData');
    };
});

无论哪种方式,您都会返回 promise 对象,而不仅仅是您从服务器获得的实际响应。可以按如下方式访问localeData

customLoader().success(function(res){
   console.log(res);
 }).error(function(){
    //show some error message
 })

答案 3 :(得分:0)

您不需要$ q 来实现您的目标:

vec (__m128 m128) //maybe take by const-ref (I don't know what __m128 is)
  : m128(m128)
{}

因为app.factory('customLoader', ["$http", "SERVER_URL", function($http, SERVER_URL) { return function(options) { return $http.post(SERVER_URL + 'getLocaleData'); }; }]); 及其所有方便方法实际上都会返回一个承诺。在这种情况下,您可以按如下方式使用此服务:

$http

如果你真的必须使用customLoader(options).success(function(localeData){ //do something here to localData }).error(function(err){ alert('warning', err.message); }); ,那么应该这样做:

$q

答案 4 :(得分:0)

通过以下方式,您可以在控制器中的工厂外访问服务器响应:

app.factory('customLoader', function ($http, $q) {
        return {
            response: {},
            getLocalData: function (param) {
                var deferred = $q.defer();
                $http.post(SERVER_URL + 'getLocaleData', param).
                    success(function (data, status, headers, config) {
                        deferred.resolve(data);
                    }).
                    error(function (data, status, headers, config) {

                    });

                return deferred.promise;
            }
        }
    });


 app.controller('yourCtrl', function($scope,customLoader) {

       $scope.GetLocaleData= function() {    
                customLoader.getLocalData({
                    Role: role,
                    Email_Id: $scope.Email,
                    Pwd: $scope.Password
                }).then(function(localeData) {
                    $scope.Data = localeData;                        
                });        
        }
 }); 
相关问题