typescript - How to generate UUID in Angular

ID : 131324

viewed : 9

Tags : angulartypescriptuuidangular

Top 4 Answer for typescript - How to generate UUID in Angular

vote vote

91

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

However, the uuid package does not define a uuid class (type); it just provides utilities for generating and parsing UUIDs as strings, and for converting between string and byte array representations. So you will not be able to use the type system to ensure that values are valid UUIDs.

vote vote

83

With the example of @MrGrigri: If you don't want to compare and keep the random numbers in an array you could do something like this and you don't need a full npm package and have control about how many groups of 4 you want

/**  * 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('-'); } 
vote vote

74

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

61

Top 3 video Explaining typescript - How to generate UUID in Angular

Related QUESTION?