如何在 Angular 中生成 UUID?
我尝试了 https://www.npmjs.com/package/uuid-generator-ts 和 https://www.npmjs.com/package/@types/uuid 这两个包。但如果我安装这些包,就会出现错误。
我尝试了 https://www.npmjs.com/package/uuid-generator-ts 和 https://www.npmjs.com/package/@types/uuid 这两个包。但如果我安装这些包,就会出现错误。
与 Angular 本身无关,你可以从一个流行的 npm 包中获取 uuid,例如:
https://www.npmjs.com/package/uuid
代码如下:
import * as uuid from 'uuid';
const myId = uuid.v4();
然而,uuid
包并没有定义一个 uuid
类(类型),它只提供用于生成和解析 UUID 作为 string
的工具,以及在 string
和字节数组表示之间进行转换的实用程序。因此,您将无法使用类型系统来确保值是有效的 UUID。
import { v4 as uuid } from 'uuid';
可以像这样使用:const myId = uuid();
- spieralanpm i --save-dev @types/uuid
- Stas Sorokin/**
* 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('-');
}
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);
}
}
const id = Date.now().toString();