import { Inject, Injectable, } from '@angular/core'; import { DOCUMENT, } from '@angular/common'; import StorageInterface from './storage.interface'; @Injectable() export default class CookieStorageService implements StorageInterface { constructor( @Inject(DOCUMENT) private _document: Document, ) {} public get( name: string, ): T { const cookieName = name + '='; const allCookies = this._document.cookie.split(';'); for (let cookie of allCookies) { while (cookie.charAt(0) === ' ') { cookie = cookie.substring(1, cookie.length); } if (cookie.indexOf(cookieName) === 0) { const cookieValue = cookie.substring( cookieName.length, cookie.length, ); try { return JSON.parse( cookieValue, ); } catch (e) { return cookieValue as any; } } } return null; } public set( name: string, data: T, ) { const modifiedData = typeof data === 'object' ? JSON.stringify(data) : data; this._document.cookie = name + '=' + modifiedData; } }