如何在Angular中生成UUID

57

1
这个回答解决了你的问题吗?如何创建GUID / UUID? - Liam
5个回答

130

与 Angular 本身无关,你可以从一个流行的 npm 包中获取 uuid,例如:

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

代码如下:

import * as uuid from 'uuid';

const myId = uuid.v4();

然而,uuid 包并没有定义一个 uuid 类(类型),它只提供用于生成和解析 UUID 作为 string 的工具,以及在 string 和字节数组表示之间进行转换的实用程序。因此,您将无法使用类型系统来确保值是有效的 UUID。


17
不要忘记添加 @types/uuid。 - charliebrownie
5
为了更方便使用,只需导入以下内容:import { v4 as uuid } from 'uuid';可以像这样使用:const myId = uuid(); - spierala
3
这个库使用了CommonJS,并在Angular中引起了警告:example.component.ts依赖于'uuid'。CommonJS或AMD依赖关系可能会导致优化失败。 - Sarah
@Sarah 没错,那么有什么替代方案呢? :) - CularBytes
5
像这样添加类型:npm i --save-dev @types/uuid - Stas Sorokin

17
以@MrGrigri为例:如果你不想进行比较并将随机数保存在一个数组中,你可以像这样做,而且你不需要一个完整的npm包,可以控制你想要多少组4个数字。
/**
 * generate groups of 4 random characters
 * @example getUniqueId(1) : 607f
 * @example getUniqueId(2) : 95ca-361a
 * @example getUniqueId(4) : 6a22-a5e6-3489-896b
 */
export function getUniqueId(parts: number): string {
  const stringArr = [];
  for(let i = 0; i< parts; i++){
    // tslint:disable-next-line:no-bitwise
    const S4 = (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    stringArr.push(S4);
  }
  return stringArr.join('-');
}

8
我知道这可能会帮助一些用户。 这是我以前所做的事情。 我创建了一个Angular的 ID Service ,用于跟踪项目中生成的所有ID。 每次生成ID时,它会与所有其他ID进行比较以确保其唯一性。 这里有一个公共属性和两个公共方法。

记住

您必须在ngOnInit方法中生成新ID,并在ngOnDestroy方法中删除该ID。 如果在组件销毁时未能删除ID,则ID数组将变得非常大。

代码

ids: string[]: 这是存储在服务中的所有唯一ID列表,以确保唯一性。

generate(): string: 此方法将生成并返回一个唯一的字符串ID; 输出:例如bec331aa-1566-1f59-1bf1-0a709be9a710

remove(id: string): void: 此方法将从存储的ID数组中删除给定的ID。

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);
  }
}

6
如果您不需要服务器端渲染(SSR),您可以使用现在被所有浏览器支持的crypto.randomUUID()方法。
const id = crypto.randomUUID();

0
一个有用的技巧:
 const id = Date.now().toString();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接