我可能犯了初学者的错误。我正试图弄清楚如何在承诺的this
部分内访问服务的then()
上下文中的函数或变量。
以下是一些示例代码:
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 :(得分: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
});
}
}]);