我正在尝试将数据存储在我的服务中,类似于以下中的答案:
Processing $http response in service
app.factory('myService', function($http) {
无功 promise ;
var myService = {
异步:函数(){
如果(! promise ){
//$http 返回一个promise,它有一个 then 函数,它也返回一个promise
promise = $http.get('test.json').then(function (response) {
//这里的 then 函数是一个修改响应的机会
控制台日志(响应);
//返回值由 Controller 中的 then 获取。
返回 response.data;
});
}
//将 promise 返回给 Controller
返回 promise ;
}
};
返回我的服务;
});
app.controller('MainCtrl', function( myService,$scope) {
$scope.clearData = function() {
$scope.data = {};
};
$scope.getData = function() {
//调用异步方法,然后对我们自己的 then 函数中返回的内容进行处理
myService.async().then(function(d) {
$scope.data = d;
});
};
});
但是,我注意到即使在注销后我的服务中的数据仍然存在。因此,我可以以完全不同的用户身份登录并查看我不应该看到的数据。
注销后如何清除数据?当然,我可以手动清除所有服务中的所有内容,但我正在寻找一种更通用的方法,例如“清除所有用户数据”。我试图强制刷新页面,并且它有效,但我不喜欢它产生的闪存。
编辑:示例中的代码
最佳答案
要清除 myService 中的数据,您可能有一个在 $scope.clearData 上调用的 destroy() 函数。
例如:
app.factory('myService',function('$http'){
/// do you stuff
return{
myServices : //...,
destroy : function(){
promise = null;//destroy promise
}
}
});
附带说明一下,您可能不想将数据存储在 $scope 中。您可能希望将控制和数据分开。
关于angularjs - 清除 AngularJs 中的服务数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23473788/