在绑定login
到service
你有,this
(如果在login
函数体使用)将指service
对象的login
执行期间。但是,在login
函数中定义的后续回调函数中,作为参数传递给.then()
,this
在执行回调函数时将不再引用服务对象,因此您需要将bind
服务作为(this
)上下文回调,或者将其存储在关闭中。因此,你可以重写你的login
功能:
// binding 'this' to the service
function login(userName, password, successCallback) {
var requestBody = 'grant_type=password&username=' + userName + '&password=' + password;
$http.post($rootScope.baseUrl + 'token', requestBody)
.then(function (response) {
this.isUserAuthenticated = true;
successCallback(response);
}.bind(this),
function (response) {
console.log(response);
});
}
要不然:
// storing the service as a closure
function login(userName, password, successCallback) {
var requestBody = 'grant_type=password&username=' + userName + '&password=' + password;
var self = this;
$http.post($rootScope.baseUrl + 'token', requestBody)
.then(
function (response) {
self.isUserAuthenticated = true;
successCallback(response);
},
function (response) {
console.log(response);
});
}
在你的情况下,后者并非绝对必要,因为你已经存储服务作为一个变量,声明在login
函数之外,并且可以简单地将true
分配给service.isAuthenticated
。
此外,如果你正在使用ES6,功能文字(即)要传递的回调.then()
可以使用脂肪箭头符号来书写,并会自动执行的背景下结合:
function login(userName, password, successCallback) {
var requestBody = 'grant_type=password&username=' + userName + '&password=' + password;
$http.post($rootScope.baseUrl + 'token', requestBody)
.then((response) => {
this.isUserAuthenticated = true;
successCallback(response);
},
(response) => {
console.log(response);
});
}
也许我误解了你的问题,但你不能只在成功回调之前做service.isUserAuthenticated = true? – zangarmarsh
确定为什么你不能只设置:service.isUserAuthenticated = true – kjonsson
你读过哪些问题?请链接它们。 – Bergi