30

in my application i need to create GUID, that GUID will be work as cookies, so anybody knows how to create GUID in angular-2/typescript or using any angular2 dependency/library.

Vinod
  • 1,234
  • 3
  • 21
  • 37

3 Answers3

22

You even can use npm to generate this for you. Follow this :

npm i guid-typescript --save

And to utilize in your code :

import { Guid } from 'guid-typescript';
export class GuidExample {
    public id: Guid;
    constructor() {
        this.id = Guid.create(); // ==> b77d409a-10cd-4a47-8e94-b0cd0ab50aa1
    }
}
Ali Eshghi
  • 1,131
  • 1
  • 13
  • 30
11

Please refer to this link, or try this npm package.

Community
  • 1
  • 1
Ali Shahzad
  • 5,163
  • 7
  • 36
  • 64
  • 2
    Also check http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript, hope it will work. – Ali Shahzad Mar 14 '17 at 09:58
  • Seems like that package produces guids that don't conform to the spec, maybe fit for your purpose but be aware. Have a look at the issues in the git repo for details. – Des Horsley Nov 10 '18 at 07:54
5

You can use this code to generate your own GUID:

class GuidGenerator {
    static newGuid() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random() * 16 | 0,
        v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
      });
    }
}
סטנלי גרונן
  • 2,917
  • 23
  • 46
  • 68