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;

     $http.get(url).then((response) => 


Which is typescript, but resolves to something like this:

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

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

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

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?



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


you can use a full page refresh:


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:



Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.