Ionic - Clear cache on logout

Ionic is an open source front-end SDK for developing hybrid mobile apps with web technologies.

Recently I was developing a relatively simple application, which has authentication too. On the profile page, there is a logout button. If the user presses it, he/she will be logged out and redirected to the login screen. A problem I encountered was that after logout, if a new user logged in (I know this happens rarely, but we need to handle it), the user data on the profile page is the old user's data. This happens because the last view is being cached, in order to be able to use the go back functionality (the back button on the navbar).

A solution would be to disable caching on the profile route. I think this is a bad idea, because it will cause diminished performance.

$stateProvider.state('profile', {
   cache: false,
   url : '/profile',
   templateUrl : 'profile.html'
});

A better solution is to clear the cache after logout. This can be done in too ways. Let's assume we have two controllers called LogoutCtrl and LoginCtrl.

The first way is to clear cache on the LogoutCtrl. We need to use a $timeout, because the cache has to be cleared after the user is redirected.

$scope.logout = function() {
      $state.go('login');

      $timeout(function () {
          $ionicHistory.clearCache();
      }, 200) 
}

This is good enough, but we can't know if 200ms are ALWAYS enough. Somehow, this will reduce the performance too.

My preferred solution is to clear cache after the user is redirected to the login screen. This can be done by using the $ionicView.enter event. You can see a list of useful events here.

$scope.$on('$ionicView.enter', function(event, viewData) {
    $ionicHistory.clearCache();
});

That's it! Hope it will help you :).