Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate UUID with angular 2?

Tags:

uuid

angular

I'm using Angular 2 for a signup form: first name, last name, email and password.

After submit, the data is being stored via API call in a database (nodeJs and mongo) and generates a JWT Token which is sent back to the client.

Now I should add/generate an UUID (Universal Unique Identifier). As I never have done this kind of feature before, I need an approach and idea/solution how to achieve this... would the JWT Token be a kind of alternative to UUID? If yes, this would be enough.

Otherwise I would prefer to avoid any big changes on the form or its functionality.

I Have been searching, but didn't find a useful solution. I tried the npm package angular2-uuid, but after installing it as dependency, the ng build -prod throws an error which isn't clear.

import { UUID } from 'angular2-uuid';
....
let uuid = UUID.UUID();

Error:

ERROR in ./~/@angular/flex-layout/@angular/flex-layout.es5.js Module build failed: Error: ENOENT: no such file or directory, open '/Users/username/dev/app/node_modules/@angular/flex- layout/@angular/flex-layout.es5.js' @ ./src/$$_gendir/app/app.module.ngfactory.ts 25:0-44 @ ./src/main.ts @ multi webpack-dev-server/client?http://localhost:4200 ./src/main.ts

Any idea or Hint please?

like image 733
k.vincent Avatar asked Aug 18 '17 10:08

k.vincent


2 Answers

It's downloaded as a part of Angular's dependency, use it like:

import { v4 as uuid } from 'uuid';

@Component(..)
export class AppComponent {

  console.log('new uid: ', uuid());
}
like image 148
Zolcsi Avatar answered Oct 21 '22 20:10

Zolcsi


For Angular 11+

  1. npm i uuid
  2. In your component, at the top where your imports are, add import { v4 as uuidv4 } from 'uuid';
  3. To test this:
ngOnInit() {
  console.log('new uid: ', uuidv4());
}
like image 40
New-Way Avatar answered Oct 21 '22 22:10

New-Way