2017-04-18 95 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