我有一个执行 http 调用的工厂,在错误回调中我想设置一个属性值,例如 this.password = null
但 this.password
不指向密码。
另一方面,当我执行 POST 时,数据发送正常:password: this.password
密码属性的范围应该不同吧?或者我还遗漏了其他东西?
.factory('LogInService', function($http) {
return {
username: null,
password: null,
logIn: function() {
return $http({
method: 'POST',
url: 'http://my-domain/api/signin',
data: {
username: this.username,
password: this.password
}
})
.then(
function(success){
},
function(err){
// reset password field
this.password = null; // <-- not working
}
);
}
}
});
我可以将所有属性和方法设置为 var 然后返回它,但我宁愿使用上面的方法。我的意思是:
var myService = {
// my property and methods...
}
errorCallBack = function(){
myService.password = null;
}
return myService;
最佳答案
您遇到了范围界定问题。做这样的事情应该很容易。一如既往,未经测试,但看起来它会起作用。
.factory('LogInService', function($http) {
return {
username: null,
password: null,
logIn: function() {
var svc = this; //<----
return $http({
method: 'POST',
url: 'http://my-domain/api/signin',
data: {
username: svc.username, //<---
password: svc.password //<---
}
})
.then(
function(success){
},
function(err){
// reset password field
svc.password = null; //<----
}
);
}
}
});
关于javascript - 在 AngularJS 中如何从服务本身内部的回调修改服务属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38594484/