简体   繁体   English

如何为每个组件实例生成一个有角度的持久唯一标识符?

[英]How to generate a angular persistent unique identifier per component instance?

I need to generate an id in order to save on DB the last filter aplied by my filter component.我需要生成一个 id 以便将我的过滤器组件应用的最后一个过滤器保存在数据库中。 the problem is that the filter component have instances in several parts of my app and I need a way to generate a persitant id for each of the instances in order to save to the DB.问题是过滤器组件在我的应用程序的几个部分都有实例,我需要一种方法来为每个实例生成一个持久的 id 以便保存到数据库。

I tried with the nghost attribuete but this one is the same in each instance.我尝试使用 nghost 属性,但在每种情况下都相同。

  private getId(): any {
    const id = this.constructor['ɵcmp'].id;
    return id;
  }

I can not depend on random generation because the id generated may change if the user change the host or the browser.我不能依赖随机生成,因为如果用户更改主机或浏览器,生成的 id 可能会更改。 Is there a way to acomplish this?有没有办法做到这一点?

this is my current sampler这是我目前的采样器

In my last attempt I add a static number var in order to get a counter for the components then add this conter to the host id在我最后一次尝试中,我添加了一个静态数字 var 以获得组件的计数器,然后将此 conter 添加到主机 ID

export class ChildComponent {
  static index = 0;
  unique = this.constructor['ɵcmp'].id + ChildComponent.index;
  constructor() {
    ChildComponent.index ++;
  }
}

This solution do not offer all I need because the generate ID can variyin depending of the order of execution of the different filters, this may caus that two filters in two diferent routes of the app get the same id.这个解决方案没有提供我需要的一切,因为生成 ID 可以根据不同过滤器的执行顺序而变化,这可能导致应用程序的两个不同路由中的两个过滤器获得相同的 ID。

To prevent this I add the Router service in order to get the current url:为了防止这种情况,我添加了 Router 服务以获取当前 url:

  constructor(private router: Router) {
    ChildComponent.index ++;
    this.unique = btoa(this.constructor['ɵcmp'].id + ChildComponent.index + this.router.url);
  }

Now I realize that if we navigate directly by url or if we navigate from the home page we get a different id for the same component instance.现在我意识到,如果我们直接通过 url 导航,或者如果我们从主页导航,我们会为同一个组件实例获得不同的 id。

If you want to create one Identifier for each instance of the component you can create your own GUID and give it to your variable unique .如果您想为组件的每个实例创建一个标识符,您可以创建自己的GUID并将其赋予您的变量unique A working example:一个工作示例:

export class ChildComponent implements OnInit{
  unique = '';

  ngOnInit() {
    this.unique = this.uuidv4()
  }

  uuidv4() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM