AgularJS: How to close active $modal on session timeout

2.4k views Asked by At

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

There are 2 answers

3
Alex P On BEST ANSWER

When the session expired you redirect user to login with

 $location.path('/login');

So in order to close all open modals in one place after redirect you can subscribe on the $routeChangeSuccess event of $rootScope and use $modalStack.dismissAll();

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

You can notify that the session ended with:

$rootScope.$broadcast('sessionEnd');

And in the controller of all your modals:

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