【发布时间】:2017-09-14 22:43:33
【问题描述】:
我有以下UserService,我只是在实例中拥有一个属性,用于确定用户是否isAuthenticated。出于某种原因,即使通过将this.isAuthenticated 设置为不同的值来更改值,在logout 和其他一些方法上,Angular 也不会捕获该更改。我什至尝试过手动编写$digest 和$apply,但仍然没有运气。
export default class UserService {
constructor($http, $state, AppConstants, JWTService) {
'ngInject';
this.$http = $http;
this.$state = $state;
this.isAuthenticated = false;
}
logout() {
this.isAuthenticated = false;
this.$state.go('login', null, { reload: true });
}
verify() {
return new Promise((resolve) => {
// if a user exists, then resolve
if (this.isAuthenticated) {
return resolve(true);
}
this.$http({
method: 'POST',
url: `${this.AppConstants.api}/verify`
})
.then(() => {
this.isAuthenticated = true;
return resolve(true);
})
.catch(() => {
this.isAuthenticated = false;
return resolve(false);
});
});
}
}
代码有效,当我第一次登录时,我将 this.isAuthenticated 设置为 true,this.verify 通过发布来工作。但是,当我logout 时,即使this.isAuthenticatd 对false 如此,当再次调用this.verify 时,条件if (this.isAuthenticated) 仍然是true。
【问题讨论】:
-
这似乎是一个 Angular v1 问题?如果是这样,请更新您的标签。
angular用于 Angular v2+,angularjs用于 Angular 1。谢谢! -
更新了标签。
标签: angular-services angularjs