在AngularJs中清除服务数据 [英] Clear service data in AngularJs
问题描述
我正在尝试将数据存储在服务中,类似于:
I'm trying to store data in my services similar to the answer in :
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.
示例代码
推荐答案
我正在使用angular-devise管理用户.这是我在注销时可以清除数据的服务:
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.
这篇关于在AngularJs中清除服务数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!