AngularJS defer确实没有返回变量

时间:2013-09-26 08:30:51

标签: javascript angularjs

我不明白为什么我的函数没有设置我的全局变量。我的代码:

 var localizeRegForm = {};


 var handlerLocalDef = function(defer) {
     var hash;

     defer.then(
         function(response) {
             return hash = response.data;
         },
         function(err) {
             showPopup(err);
         }
      );

      return hash;
  };

  var initialized = function() {
      console.log("localizeRegForm",localizeRegForm); 
      localizeRegForm = handlerLocalDef(Localization.getLocalizedDefer('regularform'));
      console.log("localizeRegForm",localizeRegForm)
  }

我的控制台显示:

  1. localizeRegForm Object {}
  2. localizeRegForm undefined

2 个答案:

答案 0 :(得分:0)

最好重写它:

        var initialized = function()  { 
                Localization.getLocalizedDefer('regularform').then(function(response){
                    localizeRegForm = response.data;
                    console.log("localizeRegForm",localizeRegForm)
                });
             }

问题不在于AngularJS, 它更多的是使用deferred object

答案 1 :(得分:0)

像这样使用

    var deferred = $q.defer();
        $http({
            method: 'POST',
            url: 'something',
            data: data
        }).
        success(function(response, status, headers, config) {
            deferred.resolve(response);
        }).
        error(function(response, status, headers, config) {
            deferred.reject("");
        })
        return deferred.promise;