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 6.9k times
27
-
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
16
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
- 947
- 1
- 11
- 24
10
Community
- 1
- 1
Ali Shahzad
- 4,787
- 7
- 31
- 62
-
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
4
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,849
- 23
- 46
- 65
Aleksandar Gordic.
- 83
- 1
- 2
-
1Should not use Math.random() - Please refer: https://bocoup.com/blog/random-numbers – Christopher Smit Apr 12 '22 at 11:56