In this tutorial, I’ll give you an example of how to use TypeScript and Angular 13 ngx-cookie-service to generate a random cookie and X-Auth token inside the browser.
Shell
x
1
1
ng new sampleapp
Shell
1
1
1
cd sampleapp
Shell
1
1
1
npm i ngx-cookie-service
app.component.html
HTML
1
11
11
1
<p>
2
Successfully set randomly generated cookie <b>X-Auth-Token</b>
3
</p>
4
<br/>
5
6
<h2>
7
<a href="https://angular-ivy-1lrgdt.stackblitz.io/" target="_blank">Click here to see the Cookie</a>
8
</h2>
9
<p>
10
Get Cookie: {{cookieValue}}
11
</p>
app.component.ts
TypeScript
1
16
16
1
import { Component, VERSION } from '@angular/core';
2
import { CookieService } from 'ngx-cookie-service';
3
import { v4 as uuidv4 } from 'uuid';
4
@Component({
5
selector: 'my-app',
6
templateUrl: './app.component.html',
7
styleUrls: ['./app.component.css']
8
})
9
export class AppComponent {
10
name = 'Angular ' + VERSION.major;
11
cookieValue = '';
12
constructor(public cookieService: CookieService) {
13
this.cookieService.set('X-Auth-Token', uuidv4());
14
this.cookieValue = this.cookieService.get('X-Auth-Token');
15
}
16
}