How to generate UUID in angular 6

本小妞迷上赌 提交于 2019-12-04 06:35:51

Nothing to do with Angular itself, you can get uuid from one of the popular npm package such as this:

https://www.npmjs.com/package/uuid

The code looks like this:

import * as uuid from 'uuid';

const myId = uuid.v4();

I know that this might help some users out there. This is what I have done in the past. I have created an Angular ID Service that keeps track of all of the ids that I have generated throughout the project. Each time an id is generated, it is checked against all of the other ids to ensure that it is unique. There are one public property and two public methods.

Remember

You must generate a new id in the ngOnInit method and remove that id in the ngOnDestroy method. If you fail to remove the id when the component is destroyed, they the ids array will get very large.

Code

ids: string[]: This is a list of all unique ids stored in the service to ensure uniqueness.

generate(): string: This method will generate and return a unique id as a string; Output: E.g. bec331aa-1566-1f59-1bf1-0a709be9a710

remove(id: string): void: This method will remove a given id from the stored ids' array.

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class IdService {
  public ids: string[] = [];

  constructor() {}

  public generate(): string {
    let isUnique = false;
    let tempId = '';

    while (!isUnique) {
      tempId = this.generator();
      if (!this.idExists(tempId)) {
        isUnique = true;
        this.ids.push(tempId);
      }
    }

    return tempId;
  }

  public remove(id: string): void {
    const index = this.ids.indexOf(id);
    this.ids.splice(index, 1);
  }

  private generator(): string {
    const isString = `${this.S4()}${this.S4()}-${this.S4()}-${this.S4()}-${this.S4()}-${this.S4()}${this.S4()}${this.S4()}`;

    return isString;
  }

  private idExists(id: string): boolean {
    return this.ids.includes(id);
  }

  private S4(): string {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!