1

我需要以下功能:當用戶轉到登錄表單時,瀏覽器應自動填充用戶名和密碼。在登錄用戶之間切換時,Angularjs模型未更新

我的實現可以在FF和Chrome上運行,但是存在這種錯誤(不一致),即在用戶之間切換時模型數據沒有正確更新。這意味着我使用用戶ONE登錄,然後註銷,然後輸入用戶TWO的憑證,但在單擊登錄按鈕後,我仍然以用戶ONE登錄。

登錄表單看起來像這樣:

<form class="form-horizontal" ng-submit="login(credentials)"> 
    <fieldset> 
     <div class="form-group" ng-class="{'has-error' : validationErrors.email}"> 
      <div class="btn-icon-lined btn-icon-round btn-icon-sm btn-default-light"> 
       <span class="glyphicon glyphicon-envelope"></span> 
      </div> 
      <input type="email" name="email" autocomplete="on" ng-model="credentials.email" class="form-control input-lg input-round text-center" placeholder="Email" > 
      <span class="help-block" ng-if="validationErrors.email">{{ validationErrors.email.0 }}</span> 
     </div> 
     <div class="form-group" ng-class="{'has-error' : validationErrors.password}"> 
      <div class="btn-icon-lined btn-icon-round btn-icon-sm btn-default-light"> 
       <span class="glyphicon glyphicon-lock"></span> 
      </div> 
      <input type="password" name="password" autocomplete="on" ng-model="credentials.password" class="form-control input-lg input-round text-center" placeholder="Password" > 
      <span class="help-block" ng-if="validationErrors.password">{{ validationErrors.password.0 }}</span> 
     </div> 
     <div class="form-group"> 
      <input type="submit" value="Sign in" class="btn btn-primary btn-lg btn-round btn-block text-center"> 
     </div> 
    </fieldset> 
</form> 

登錄控制器包含這樣的:

// Login Controller 
app.controller('LoginCtrl', ['$rootScope','$scope', '$state', 'AppUser', 'Auth', 
    function($rootScope, $scope, $state, AppUser, Auth){ 

    console.log("LoginCtrl"); 

    $scope.credentials = { 
     "email" : "", 
     "password": "" 
    }; 

    $scope.redirectAfterLogin = function() { 
     // set user data 
     AppUser.setUserData($scope.user); 
     ... 
    } 

    // Login attempt handler 
    $scope.login = function(data) { 
     data = {'user':data}; 

     Auth.login(data, 
      function(response) { 
       $scope.user = response.data; 

       ... 

      },function(response){ 
       $scope.validationErrors = { 
        "email" : [], 
        "password": [] 
       }; 
       ... 
      } 

     ); 
    }; 

}]); 

註銷:

// logout 
$scope.logout = function() { 
    // remove attempted URL, if any 
    AppUser.removeAttemptUrl(); 

    data = {'user': 
     { 
      'email': $scope.user.email 
     } 
    }; 
    Auth.logout(data, 
     function(){ 
      AppUser.unSetUserData($scope.user); // se method below 
      $state.go(ApplicationState.LOGIN); 
     }, 
     function(){ 
      console.log("Logout failed"); 
    }); 
} 

angular.module('app.service').factory('AppUser', [ 
'$window', '$rootScope', 'LocalStorage', 'appConfig', '$injector', '$location', 
function($window, $rootScope, localStorage, appConfig, $injector, $location){ 

// Redirect to the original requested page after login 
var redirectToUrlAfterLogin = { url: '' }; 
var userKey = "AppUser"; 
var userData = {}; 

angular.element($window).on('storage', function(event) { 
    if (event.key === userKey) { 
     $rootScope.$apply(); 
    } 
}); 

return { 

    /** 
    * Redirect to the original requested page after login 
    * - we need to be able to save the intended URL, request it, remove it and redirect to it 
    */ 
    saveAttemptUrl: function() { 
     if ($location.path().toLowerCase() != ApplicationState.LOGIN) { 
      redirectToUrlAfterLogin.url = $location.path(); 
     } 
     else { 
      redirectToUrlAfterLogin.url = '/'; 
     } 
    }, 
    getAttemptedUrl: function() { 
     return redirectToUrlAfterLogin.url; 
    }, 
    removeAttemptUrl: function() { 
     // re-initialize URL 
     redirectToUrlAfterLogin = { url: '' }; 
    }, 
    redirectToAttemptedUrl: function() { 
     $location.path(redirectToUrlAfterLogin.url); 
    }, 

    /** 
    * Returns the current user's state 
    * @returns {boolean} 
    */ 
    isAuthenticated: function() { 
     userData = JSON.parse(localStorage.get(userKey) || '{}').userData; 

     if (!this._isSessionExpired()) { 
      if (userData !== undefined){ 
       return !!(userData.id !== null && userData.email); 
      } 
      else{ 
       return false; 
      } 
     } 
     else{ 
      if (userData !== undefined){ 
       var data = { 
        'user':{ 
         'email': userData.email 
        } 
       } 

       // we use $injector to avoid Circular Dependency which is thrown by injecting the $api service 
       $injector.invoke(['$api', function($api){ 
        $api.auth.logout(data).success(function(result){ 
         userData = {}; 
         localStorage.remove(userKey); 
        }); 
       }]); 
       return false; 
      } 
     } 
    }, 

    getUserData: function() { 
     return userData; 
    }, 

    setUserData: function(data) { 
     userData = data; 
     localStorage.set(userKey, JSON.stringify({ 
      userData: data, 
      stamp: Date.now() 
     })); 
    }, 

    unSetUserData: function() { 
     userData = {}; 

     localStorage.remove(userKey); 
    }, 

    _isSessionExpired: function() { 
     var session = JSON.parse(localStorage.get(userKey) || '{}'); 
     return (Date.now() - (session.stamp || 0)) > appConfig.sessionTimeout; 
    }, 

    userData : userData 
}; 

}]);

爲什麼會發生這種情況的任何想法?

+1

你可以添加註銷碼嗎?我懷疑你沒有在任何地方清除$ scope.credentials.email和$ scope.credentials.password –

+0

註銷時會發生什麼?聽起來你沒有在註銷時刪除AppUser服務中的任何用戶數據。您能否請您告訴我們您的註銷碼。 –

+0

當然,我添加了註銷代碼。 –

回答

1

退出後,用瀏覽器檢查器檢查localStorage
也許你會發現一些你沒有清楚的變量。 所以只需清除存儲空間,它應該沒問題。

要清除存儲使用:

localStorage.clear(); 

一個額外的問題,也可能是你沒有清潔$rootScope如果你沒有刷新所有數據仍然在那裏。

+0

在註銷後我在locaStorage中有這樣的東西:AppUser「{」stamp「:1436791992992}」 –

+0

我在註銷時使用了localStorage.clear();在登錄頁面(在註銷後使用登錄表單)檢查localStorage內容時,我仍然有AppUser:{stamp:123 ..}條目。 –

+0

嘗試在檢查器中放置一個斷點以查看您是否使用localStorage.clear( ); https:// dev eloper.chrome.com/devtools/docs/javascript-debugging – borracciaBlu

0

這是問題嗎? userKey似乎沒有在您展示的代碼中定義。

// add userKey param 
unSetUserData: function(userKey) { 
    userData = {}; 

    localStorage.remove(userKey); 
}, 
+0

對不起,我更新了代碼,我沒有想到要添加該代碼。我定義了一個服務:angular.module('sgApp.service')。factory('AppUser',[...]處理所有與用戶有關的功能。我相信問題存在於邏輯中的某個地方(我沒有控制檯和登錄/註銷錯誤已經持續數月了) –

+0

如果我們可以看到代碼是完整的而不是編輯版本,那會更容易一些,我們可以看到未經編輯的AppUser服務版本嗎? –

+0

Sure ,我在我的問題中添加了完整的AppUser服務 –

相關問題