首页 文章

清除AngularJs中的服务数据

提问于
浏览
5

我正在尝试将数据存储在我的服务中,类似于以下答案:

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;
    });
  };
});

但是,我注意到即使在注销后我的服务中的数据仍然存在 . 因此,我可以作为一个完全不同的用户登录,看到我不应该看到的数据 .

注销后如何清除数据?当然,我可以手动清除所有服务中的所有内容,但我正在寻找更通用的方法,例如“清除所有用户数据” . 我试图强制页面刷新,它可以工作,但我不喜欢它产生的闪存 .

编辑:示例中的代码

2 回答

  • 0

    要清除myService中的数据,可能有一个在$ scope.clearData上调用的destroy()函数 . 例如:

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

    另外,您可能不希望将数据存储在$ scope中 . 您可能希望分离控制和数据 .

  • 0

    我正在使用angular-devise来管理我的用户 . 以下是我在服务中清除注销数据的方法:

    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;
      });
    });
    

    我很想找到一种更可靠的方法来销毁服务中的敏感对象 . 这解决了我的问题 .

相关问题