2015-09-15 121 views
0

我可能是一個初學者的錯誤。我試圖弄清楚如何在this服務的上下文中訪問函數或變量,而在承諾的then()部分。AngularJs服務訪問服務上下文的內容然後()上下文

下面是一些示例代碼:

ndtApp.service("userService", ['$http', 
function($http){ 

    this.saveLoginInfo = function(data){ 
     //do some stuff here. 
    } 

    this.login = function(){ 
     //Login 
     $http.get('http://example.com/userlogin').then(
      function(data){ 
       this.saveLoginInfo(data); 
       //This won't work because 'this' from here is 'window' rather than the service. 
      }, 
      function(data){ 
       //error handling 
      }); 
    } 

}]); 

如何到達saveLoginInfo功能?

+0

約翰帕帕建議[使用一個變量來捕獲'this'因爲這個原因](https://github.com/johnpapa/angular-styleguide#style-y032)。 – sgbj

+0

這是一個很棒的閱讀,謝謝! – Coo

回答

3

當您在JS中輸入函數時,上下文更改爲當前函數。你可以指定this來解決範圍問題。

ndtApp.service("userService", ['$http', 
function($http){ 
var self = this; 
self.saveLoginInfo = function(data){ 
    //do some stuff here. 
} 

self.login = function(){ 
    //Login 
    $http.get('http://example.com/userlogin').then(
     function(data){ 
      self.saveLoginInfo(data); 
      //This won't work because 'this' from here is 'window' rather than the service. 
     }, 
     function(data){ 
      //error handling 
     }); 
} 

}]); 
+0

這確實工作。後續問題:現在在'window'中定義了'self'嗎?這不是一個問題/我們應該避免的麻煩? – Coo

+0

@Coo self在服務的上下文中定義。它可用於您在服務中定義的任何功能。我建議閱讀鏈接的樣式指南sbat。這是一個很好的資源 – jfadich

+0

謝謝你!我確實閱讀了風格指南,這使我開始使用IIFE解決了我的污染問題。 – Coo