2014-07-23 153 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