AgularJS: How to close active $modal on session timeout

时间:2015-06-26 10:25:45

标签: angularjs session-timeout angularjs-routing bootstrap-modal

I'm developing a SPA, on session timeout i will redirect the user to login page. Here is my implementation

.run(['$rootScope', '$state', '$location', function ($rootScope, $state, $location) {

    $rootScope.$watch(function detectIdle() {

    var now = new Date();

     if (now - lastDigestRun > 20 * 60 * 1000) {

        $location.path('/login');

        setTimeout(function () {
          alert("Your session has expired. Please log in again");
        }, 1000); 
     }
   });

}])

Problem: If application timeouts when some $modal is open, page redirect to login page but $modal will not close.

please help me to solve the problem

Thanks

Update: Sorry for answering my own question, Working Solution given below:

 .run(['$rootScope', '$state', '$location', function ($rootScope, $state, $location) {

    var isSessionTimeout = false; 

    $rootScope.$watch(function detectIdle() {

    var now = new Date();

     if (now - lastDigestRun > 20 * 60 * 1000) {

        isSessionTimeout = true;
        $location.path('/login');

        setTimeout(function () {
          alert("Your session has expired. Please log in again");
        }, 1000); 
     }
   });

  $rootScope.$on('$stateChangeSuccess', function () {
    if (isSessionTimedOut) {
        $modalStack.dismissAll();
    }             
 });

}])

2 个答案:

答案 0 :(得分:1)

您可以通过以下方式通知会话结束:

$rootScope.$broadcast('sessionEnd');

在所有模态的控制器中:

$scope.$on('sessionEnd', function() {
    $modalInstance.dismiss();
});

答案 1 :(得分:1)

会话过期后,您将用户重定向到

登录
 $location.path('/login');

因此,为了在重定向后在一个地方关闭所有打开的模态,您可以订阅 $ routeChangeSuccess $ rootScope事件并使用$modalStack.dismissAll();

 app.run(['$rootScope', '$modalStack', function ($rootScope, $modalStack) {
    $rootScope.$on('$routeChangeSuccess', function () {
        $modalStack.dismissAll();
    });
 }]);