我将尝试添加一些与UUID相关的软件包,即https://www.npmjs.com/package/uuid-generator-ts和https://www.npmjs.com/package/@types/uuid。但是我遇到一个错误,如果我安装了这些软件包,请告诉我如何在角度6中生成UUID。
Xin*_*nan 27
与Angular本身无关,您可以从流行的npm软件包之一中获取uuid,例如:
https://www.npmjs.com/package/uuid
代码如下:
import * as uuid from 'uuid';
const myId = uuid.v4();
Run Code Online (Sandbox Code Playgroud)
以@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('-');
}
Run Code Online (Sandbox Code Playgroud)
如果您不需要服务器端渲染(SSR),则可以使用现在所有现代浏览器都支持的crypto.randomUUID()方法。
const id = crypto.randomUUID();
Run Code Online (Sandbox Code Playgroud)
我知道这可能会帮助一些用户。这就是我过去所做的。我创建了一个 AngularID Service来跟踪我在整个项目中生成的所有 id。每次生成一个 id 时,它都会与所有其他 id 进行检查以确保它是唯一的。有一个公共属性和两个公共方法。
您必须在ngOnInit方法中生成一个新 id 并在方法中删除该 id ngOnDestroy。如果在组件销毁时未能删除 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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23366 次 |
| 最近记录: |