Clear service data in AngularJs

2019-04-29 14:12发布

I'm trying to store data in my services similar to the answer in :

Processing $http response in service

app.factory('myService', function($http) {
  var promise;
  var myService = {
    async: function() {
      if ( !promise ) {
        // $http returns a promise, which has a then function, which also returns a promise
        promise = $http.get('test.json').then(function (response) {
          // The then function here is an opportunity to modify the response
          console.log(response);
          // The return value gets picked up by the then in the controller.
          return response.data;
        });
      }
      // Return the promise to the controller
      return promise;
    }
  };
  return myService;
});

app.controller('MainCtrl', function( myService,$scope) {
  $scope.clearData = function() {
    $scope.data = {};
  };
  $scope.getData = function() {
    // Call the async method and then do stuff with what is returned inside our own then function
    myService.async().then(function(d) {
      $scope.data = d;
    });
  };
});

However, I noticed that the data in my services persists even after logout. Thus I could login as a completely different user and see data which I should not see.

How can I clear data after logout? Sure I could manually clear everything in all my services, but I am looking for a more general approach such as "clear all user data". I have tried to force a page refresh, and it works, but I don't like the flash it produces.

edit: Code from example

2条回答
该账号已被封号
2楼-- · 2019-04-29 14:39

To clear the data in myService, you may have a destroy() function that is called upon $scope.clearData. For example:

app.factory('myService',function('$http'){
   /// do you stuff
   return{
     myServices : //...,
     destroy : function(){
       promise = null;//destroy promise
     }
   }
});

On a side note, you probably don't want to store data in $scope. You may want to separate controlling and data.

查看更多
Anthone
3楼-- · 2019-04-29 14:58

I'm using angular-devise to manage my users. Here's what I have in my service to clear data on logout:

app.service("MyService", ["$rootScope", function($rootScope) {
  // destroy the user data on logout
  self = this;
  this.shouldBeDestroyed = "foo";

  $rootScope.$on('devise:logout', function(event) {
    self.shouldBeDestroyed = null;
  });
});

I'd love to find a more reliable way to destroy sensitive objects in services. This solved my problem though.

查看更多
登录 后发表回答