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.
Asked
Active
Viewed 8.3k times
30
-
http://stackoverflow.com/a/105074/1876949 – Sasxa Mar 14 '17 at 09:54
-
Possible duplicate of [How to generate UUID with angular 2?](https://stackoverflow.com/questions/45754907/how-to-generate-uuid-with-angular-2) – BuZZ-dEE May 24 '19 at 07:53
3 Answers
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
-
1pacakge [`uuid`](https://www.npmjs.com/package/uuid) is more popular; `npm i uuid @types/uuid` – xinthose Dec 28 '22 at 19:07
11

Community
- 1
- 1

Ali Shahzad
- 5,163
- 7
- 36
- 64
-
2Also 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

Aleksandar Gordic.
- 93
- 1
- 2
-
1Should not use Math.random() - Please refer: https://bocoup.com/blog/random-numbers – Christopher Smit Apr 12 '22 at 11:56