我可能是一個初學者的錯誤。我試圖弄清楚如何在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
功能?
約翰帕帕建議[使用一個變量來捕獲'this'因爲這個原因](https://github.com/johnpapa/angular-styleguide#style-y032)。 – sgbj
這是一個很棒的閱讀,謝謝! – Coo