2014-07-23 112 views
0

内的子功能中我有以下服务:访问变量的服务功能

function Configuration($http, $q) { 
    this.$http = $http; 
    this.$q = $q; 

    this.promises = []; 

    this.getEnv().then(function(d) { 
     this.env = d; 
    }); 
} 

Configuration.prototype.getEnv = function() { 

    // only go get the environment setting if we don't already have it 

    var deferred = this.$q.defer(); 

    if (this.promises.length > 0) { 

     console.log('%cAdd to queue', 'color:orange;'); 
     this.promises.push(deferred); 

    } else if (!this.env) { 
     this.promises.push(deferred); 
     console.log('%cFetch from live', 'color:red'); 

     // $http returns a promise, which has a then function, which also returns a promise 
     var promise = this.$http.get('config/env.json').then(function(response) { 
      // The then function here is an opportunity to modify the response 
      console.log("environment variable is " + response.data.current_environment); 
      // The return value gets picked up by the then in the controller. 
      this.env = response.data.current_environment; 

      var i; 
      for (i = this.promises.length; i--;) { 
       console.log('%cYay! Resolving the existing promises with a single server side request', 'color:white;background:deepskyblue'); 
       this.promises.shift().resolve(this.env); 
      } 
     }); 
    } else { 
     console.log('%cFetch direct from this.env', 'color:green'); 
     deferred.resolve(this.env); 
    } 

    // Return the promise to the controller 
    return deferred.promise; 
}; 

我在调试我建立以防止多个命中服务器的承诺缓存的过程。不幸的是,Chrome中的JS引擎比Apache快得多。这个概念很简单,基本上将承诺记录在缓存中,如果方法被击中,缓存中没有承诺,运行它,如果缓存中有承诺,则不执行它。

我的问题发生在for (i = this.promises.length; i--;) {会发生什么是this.promises是未定义的。我假设它是因为它的嵌套函数内部和它的正常JS变量作用域不允许它访问父函数中的变量。但我不知道。

有没有办法让这项工作?

回答

3

可以缓存this$http承诺回调外,因为回调中你不再是你的服务实例的上下文: -

var _this = this; //<-- Here 

    var promise = this.$http.get('config/env.json').then(function(response) { 


     _this.env = response.data.current_environment; 

     var i; 
     for (i = _this.promises.length; i--;) { 

      _this.promises.shift().resolve(_this.env); 
     } 
    }); 

或绑定服务实例的上下文回调。

this.$http.get('config/env.json').then((function(response) { 
     // The then function here is an opportunity to modify the response 
     console.log("environment variable is " + response.data.current_environment); 
     // The return value gets picked up by the then in the controller. 
     this.env = response.data.current_environment; 

     var i; 
     for (i = this.promises.length; i--;) { 
      console.log('%cYay! Resolving the existing promises with a single server side request', 'color:white;background:deepskyblue'); 
      this.promises.shift().resolve(this.env); 
     } 
    }).bind(this)) 
+0

美丽,我觉得这是愚蠢的。你的第一个人就像一个魅力。第二个没有出于某种原因。不知道为什么。但无论如何,谢谢 – scphantm