Angular 5+ cookies service. Very handy tool for manipulating with browser cookies.
Inspired by AngularJS 1.x.x cookies service. This service contains all those methods with some improvements.
$ npm install --save ngboost-cookies
This is standalone library which doesn't require any extrenal dependencies.
// app.module.ts
import { CookiesService } from 'ngboost-cookies';
@NgModule({
declarations: [],
imports: [],
providers: [
CookiesService,
],
bootstrap: [AppComponent]
})
export class AppModule { }
// some.component.ts
private cookieOpts;
constructor(private cookiesService: CookiesService) {
this.cookieOpts = {
domain: 'example.com',
path: '/',
// expires: 5, // expires after 5 days
expires: new Date('2018-10-31T03:24:00'),
secure: false,
httpOnly: false,
sameSite: 'strict'
};
}
login() {
this.cookiesService.putObject('authAPI', cookie_val, this.cookieOpts, false);
}
interface CookieOptions {
domain?: string;
path?: string;
expires?: number | Date; // number of days or exact date
secure?: boolean;
httpOnly?: boolean;
sameSite?: string; // 'strict' for GET and POST, 'lax' only for POST
}
domain - [string] cookie domain
path - [string] specific cookie path
expires - [number | Date] define cookie expiration time (in days or exact day/time)
secure - [boolean] Cookie to only be transmitted over secure protocol as https.
httpOnly - [boolean] additional flag
sameSite - ['strict' | 'lax'] prevents the browser from sending this cookie along with cross-site requests, 'strict' for POST and GET, 'lax' only for POST
Set cookie. Cookie value is string.
Set cookie. Cookie value is object.
Get all cookies in string format. For example: 'cook1=jedan1; cook2=dva2;'.
Get cookie by specific name. Returned value is string.
Get cookie by specific name. Returned value is object.
Remove cookie by specific name.
Remove all cookies.
Empty cookie value by specific name.
Check if cookie exists.
Created by Saša Mikodanić under MIT licence.