在AngularJs中注销时清除服务中数据的最佳实践 [英] Best practices for Clearing data in services on logout in AngularJs

查看:75
本文介绍了在AngularJs中注销时清除服务中数据的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个使用Web服务的服务并缓存了很多结果。通过缓存我的意思是存储在服务的变量中。当用户注销时,应清除数据。
服务如下所示(简化版):

I have several services which uses a webservice and caches a lot of the results.By caching i mean storing in a variable on the service. When a user logs out the data should be cleared. The services looks like the following (simplified version):

class DataService   {

  private data;

  constructor($http)
  {
     $http.get(url).then((response) => 
       { 
          this.data = response.data;
       });
  }

}

哪个是打字稿,但解析如下:

Which is typescript, but resolves to something like this:

var DataService = (function () {
    function DataService($http) {
        var _this = this;
        $http.get(url).then(function (response) {
            _this.data = response.data;
        });
    }
    return DataService;
})();

我可以使用这个问题
这是做这样的事情:

I could clear the data using the answer in This Question Which is doing something like this:

$rootScope.on('logout',function(){
  this.data = [];
});

但是,当我们有多个服务和控制器时,这是很多代码。我们都知道这个新人会在服务中添加一些新数据,并忘记将其添加到注销序列中。这简直是​​一种不好的做法。

However, this is a lot of code when we have multiple services and controllers. And we all know that this new guy will add some new data to a service and he forgets to add it to the logout sequence. It is simply a bad practice.

类似地,数据存储在应用程序各个部分的$ scope中,这也必须清除。
范围相当简单,因为控制器的构造函数在每次页面访问时加载,然后将覆盖数据。

Similarily, data are stored on $scope in various parts of the application and this must be cleared as well. The scope is rather simple as constructors for the controllers are loaded on each page visits and will then override the data.

一个提议的解决方案是进行刷新,但这会给用户带来可怕的体验。

One propossed solution is to make a refresh, however this gives horrible user experiences.

一种解决方案可能是让角度相信从未创建过服务或完全重新加载角度。

One solution could be to make angular believe that the services have never been created or reload angular completely.

这样做的最佳方式是什么?将数据存储在服务上的变量中是不是很糟糕?

What is the best way to do this? Is it bad to store data in variables on services?

推荐答案

您可以创建一个负责清除所有数据的服务其他服务。在这种情况下,您只需要调用此服务的 clear 方法,并在此内部实现单独的clear调用(因此只实现一次)。

You can create a service which is responsible clearing all the the data from the other services. In this case you only have to call the "clear" method of this service, and implement the individual clear calls inside of this one (so only implemented once).

这也为您提供了一个优势,即您可以随时了解哪些服务数据需要清除,因为将来可能会有例外。

This gives you also the advantage that you have an overview of which services data need to be cleared all the time, since you might have exceptions in the future.

另请参阅此答案供您参考:在angularJS中将服务注入另一个服务

Also see this answer for your reference: Injecting a service into another service in angularJS

这篇关于在AngularJs中注销时清除服务中数据的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆