2017-04-18 96 views
0

我有以下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,条件if (this.isAuthenticated)仍然是true时,再次调用this.verify

+0

这似乎是一个角v1的问题吗?如果是这样,请更新您的代码。 'angular'用于Angular v2 +,'angularjs'用于角度1.谢谢! – DeborahK

+0

更新了标签。 – Detuned

回答

0

“this”不是你认为它在你的.then()函数中。范围已经改变。这种情况很常见,只是在使用javascript时必须牢记在心。这只是其中的一个,你可以做些什么例子:

javascript promises and "this"

+0

由于我们使用胖箭头语法,我知道'this'是什么,因为上下文保持不变。我已经测试过,以确保我们处于相同的环境中。 – Detuned