Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices for Clearing data in services on logout in AngularJs

I have several services which uses a webservice and caches a lot of the results.By caching i mean storing in a variable on the service. When a user logs out the data should be cleared. The services looks like the following (simplified version):

class DataService   {

  private data;

  constructor($http)
  {
     $http.get(url).then((response) => 
       { 
          this.data = response.data;
       });
  }

}

Which is typescript, but resolves to something like this:

var DataService = (function () {
    function DataService($http) {
        var _this = this;
        $http.get(url).then(function (response) {
            _this.data = response.data;
        });
    }
    return DataService;
})();

I could clear the data using the answer in This Question Which is doing something like this:

$rootScope.on('logout',function(){
  this.data = [];
});

However, this is a lot of code when we have multiple services and controllers. And we all know that this new guy will add some new data to a service and he forgets to add it to the logout sequence. It is simply a bad practice.

Similarily, data are stored on $scope in various parts of the application and this must be cleared as well. The scope is rather simple as constructors for the controllers are loaded on each page visits and will then override the data.

One propossed solution is to make a refresh, however this gives horrible user experiences.

One solution could be to make angular believe that the services have never been created or reload angular completely.

What is the best way to do this? Is it bad to store data in variables on services?

like image 319
CodeTower Avatar asked Oct 23 '14 07:10

CodeTower


2 Answers

You can create a service which is responsible clearing all the the data from the other services. In this case you only have to call the "clear" method of this service, and implement the individual clear calls inside of this one (so only implemented once).

This gives you also the advantage that you have an overview of which services data need to be cleared all the time, since you might have exceptions in the future.

Also see this answer for your reference: Injecting a service into another service in angularJS

like image 79
Torsten Engelbrecht Avatar answered Oct 24 '22 11:10

Torsten Engelbrecht


you can use a full page refresh:

$window.location.reload();

this will restart the whole state of your application

another solution could be to store everything in session storage and then clear it on log out:

sessionStorage.clear();
like image 31
Marian Ban Avatar answered Oct 24 '22 11:10

Marian Ban