【问题标题】:How to generate UUID in Angular如何在 Angular 中生成 UUID
【发布时间】:2021-03-11 15:51:19
【问题描述】:

如何在 Angular 中生成 UUID?

我尝试了 https://www.npmjs.com/package/uuid-generator-tshttps://www.npmjs.com/package/@types/uuid 包。但是如果我安装这些软件包,我会收到错误,

【问题讨论】:

标签: angular typescript uuid


【解决方案1】:

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

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

代码如下所示:

import * as uuid from 'uuid';

const myId = uuid.v4();

但是,uuid 包确实定义了 uuid 类(类型);它只提供用于生成和解析 UUID 为 strings 以​​及在 string 和字节数组表示之间转换的实用程序。因此,您将无法使用类型系统来确保值是有效的 UUID。

【讨论】:

  • 别忘了添加@types/uuid
  • 只是另一个更容易使用的导入:import { v4 as uuid } from 'uuid'; 可以这样使用:const myId = uuid();
  • 这个库使用 CommonJS 并在 Angular 中引起警告:example.component.ts 依赖于 'uuid'。 CommonJS 或 AMD 依赖项可能导致优化救助。
  • @Sarah 完全正确,那么有什么替代方案呢? :)
  • 添加这样的类型:npm i --save-dev @types/uuid
【解决方案2】:

以@MrGrigri 为例:如果您不想比较随机数并将其保存在一个数组中,您可以执行这样的操作,并且您不需要完整的 npm 包并且可以控制有多少组4个你想要的

/**
 * generate groups of 4 random characters
 * @example getUniqueId(1) : 607f
 * @example getUniqueId(2) : 95ca-361a-f8a1-1e73
 */
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('-');
}

【讨论】:

    【解决方案3】:

    我知道这可能会帮助一些用户。这就是我过去所做的。我创建了一个 Angular ID Service 来跟踪我在整个项目中生成的所有 id。每次生成一个 id 时,都会与所有其他 id 进行检查,以确保它是唯一的。有一种公共属性和两种公共方法。

    记住

    您必须在 ngOnInit 方法中生成一个新 id,并在 ngOnDestroy 方法中删除该 id。如果在组件销毁时没有移除 id,ids 数组会变得非常大。

    代码

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

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

    remove(id: string): void: 此方法将从存储的 ids 数组中删除给定的 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);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-01-18
      • 2017-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-05-23
      • 2021-08-29
      相关资源
      最近更新 更多