How to set cookie in Angular?

Setting Cookies in Angular: A Comprehensive Guide

Introduction

In this article, we will explore the process of setting cookies in Angular, a popular JavaScript framework for building web applications. Cookies are small text files stored on a user’s device, and they can be used to store data that is specific to the user’s session or application. In this guide, we will cover the basics of setting cookies in Angular, including how to create, read, and delete cookies.

Creating Cookies in Angular

To create a cookie in Angular, you need to use the HttpClient service, which provides a way to send HTTP requests to the server. Here’s an example of how to create a cookie using the HttpClient service:

import { HttpClient } from '@angular/common/http';

const http = new HttpClient();

const cookie = {
name: 'session_id',
value: '1234567890',
expires: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000)
};

http.post('/set-cookie', cookie)
.subscribe((response) => {
console.log(response);
});

In this example, we create a cookie object with the following properties:

  • name: The name of the cookie.
  • value: The value of the cookie.
  • expires: The expiration date of the cookie.

We then use the HttpClient service to send a POST request to the /set-cookie endpoint, passing the cookie object as a JSON payload.

Reading Cookies in Angular

To read a cookie in Angular, you need to use the HttpClient service again, but this time you need to send a GET request to the /get-cookie endpoint. Here’s an example of how to read a cookie using the HttpClient service:

import { HttpClient } from '@angular/common/http';

const http = new HttpClient();

const cookie = {
name: 'session_id',
value: '1234567890',
expires: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000)
};

http.get('/get-cookie', { params: cookie })
.subscribe((response) => {
console.log(response);
});

In this example, we create a cookie object with the same properties as before, and then use the HttpClient service to send a GET request to the /get-cookie endpoint, passing the cookie object as a JSON payload.

Deleting Cookies in Angular

To delete a cookie in Angular, you need to use the HttpClient service again, but this time you need to send a DELETE request to the /delete-cookie endpoint. Here’s an example of how to delete a cookie using the HttpClient service:

import { HttpClient } from '@angular/common/http';

const http = new HttpClient();

const cookie = {
name: 'session_id',
value: '1234567890',
expires: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000)
};

http.delete('/delete-cookie', { params: cookie })
.subscribe((response) => {
console.log(response);
});

In this example, we create a cookie object with the same properties as before, and then use the HttpClient service to send a DELETE request to the /delete-cookie endpoint, passing the cookie object as a JSON payload.

Cookies in Angular Forms

Cookies can also be used in Angular forms to store data that is specific to the user’s session or application. Here’s an example of how to use cookies in Angular forms:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
selector: 'app-example',
template: `
<form (ngSubmit)="onSubmit()">
<label>Username:</label>
<input type="text" [(ngModel)]="username">
<br>
<label>Password:</label>
<input type="password" [(ngModel)]="password">
<br>
<button type="submit">Submit</button>
</form>
`
})
export class ExampleComponent implements OnInit {
username: string;
password: string;

constructor(private http: HttpClient) { }

ngOnInit(): void {
}

onSubmit(): void {
const cookie = {
name: 'session_id',
value: '1234567890',
expires: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000)
};

this.http.post('/set-cookie', cookie)
.subscribe((response) => {
console.log(response);
});
}
}

In this example, we create a form with two input fields, one for the username and one for the password. We then use the HttpClient service to send a POST request to the /set-cookie endpoint, passing the username and password as a JSON payload.

Cookies in Angular Routing

Cookies can also be used in Angular routing to store data that is specific to the user’s session or application. Here’s an example of how to use cookies in Angular routing:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
selector: 'app-example',
template: `
<router-outlet></router-outlet>
`
})
export class ExampleComponent implements OnInit {
username: string;

constructor(private router: Router) { }

ngOnInit(): void {
}

onSubmit(): void {
const cookie = {
name: 'session_id',
value: '1234567890',
expires: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000)
};

this.router.navigate(['/login', cookie.name]);
}
}

In this example, we create a router outlet and pass the username as a parameter to the /login route. We then use the HttpClient service to send a GET request to the /login endpoint, passing the username as a JSON payload.

Conclusion

In this article, we have covered the basics of setting cookies in Angular, including how to create, read, and delete cookies. We have also discussed how to use cookies in Angular forms and routing. By following these examples, you can use cookies to store data that is specific to the user’s session or application in your Angular applications.

Table of Contents

Unlock the Future: Watch Our Essential Tech Videos!


Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top