1

What is the best practice in clearing service data for AngularJS. For example if user1 logs out and a user2 logs back in on the same browser, if I am not clearing the service data, then user2 will be using the same service data as user1.

For example in the code below, if user1 added more users to the service and logged out, and in the same browser, if user2 logged back in, they would be able to see all the users user1 added.

var module = angular.module('myapp', []);

module.service('userService', function(){
    var users = ['John', 'James', 'Jake'];
});

I have two solutions to tackle this problem but none are ideal.

  1. Manually reset every single property in the service. This does not seem to be an ideal solution because someone might forget to do that someday.
  2. Reload window on logout. Seems to reset the service but it is somewhat poor user experience.

Is there a better alternative?

m0g
  • 969
  • 2
  • 15
  • 30
  • It depend on many parameters, and your question is currently too broad to answer. You can try https://github.com/witoldsz/angular-http-auth - Allow you to handle logout/unauthorized requests using events – Alon Eitan Jul 13 '16 at 21:39
  • I am already using an interceptor. What I would would like to know is during the log out event, how can I efficiently clear the service state? – m0g Jul 13 '16 at 21:45
  • Again, it also depends on your code - Do you store the data in a localStorage, variables? It would be best if you could also include some code in the question, are you using the `ui-route` module or just `ngRoute`. Too many unknown factors – Alon Eitan Jul 13 '16 at 21:48
  • Sorry my question has to do with service state in Angular. I added more description. Hope it helps. – m0g Jul 13 '16 at 21:59
  • sounds like issue is partly due to poor design of service in the first place. Simply not enough known for anyone to provide constructive help – charlietfl Jul 13 '16 at 22:06
  • I simply want a nice way to reset the service state in Angular without having to reload the webpage. It really has nothing to do with implementation. – m0g Jul 14 '16 at 00:51
  • this SO question has some good suggestions in it: http://stackoverflow.com/questions/23473788/clear-service-data-in-angularjs – Yvonne Aburrow Oct 06 '16 at 10:37

1 Answers1

1

On logout:

window.location.href = "yourloginurl";

It doesn't matter if logging out isn't as snappy as the rest of your SPA.

Andrew Gee
  • 338
  • 1
  • 12