tryit tag style attribute javascript angular typescript

javascript - tag - Galletas angulares



title tag html (7)

Hago Miquels Version Injectable como servicio:

import { Injectable } from ''@angular/core''; @Injectable() export class CookiesService { isConsented = false; constructor() {} /** * delete cookie * @param name */ public deleteCookie(name) { this.setCookie(name, '''', -1); } /** * get cookie * @param {string} name * @returns {string} */ public getCookie(name: string) { const ca: Array<string> = document.cookie.split('';''); const caLen: number = ca.length; const cookieName = `${name}=`; let c: string; for (let i = 0; i < caLen; i += 1) { c = ca[i].replace(/^/s+/g, ''''); if (c.indexOf(cookieName) === 0) { return c.substring(cookieName.length, c.length); } } return ''''; } /** * set cookie * @param {string} name * @param {string} value * @param {number} expireDays * @param {string} path */ public setCookie(name: string, value: string, expireDays: number, path: string = '''') { const d: Date = new Date(); d.setTime(d.getTime() + expireDays * 24 * 60 * 60 * 1000); const expires = `expires=${d.toUTCString()}`; const cpath = path ? `; path=${path}` : ''''; document.cookie = `${name}=${value}; ${expires}${cpath}`; } /** * consent * @param {boolean} isConsent * @param e * @param {string} COOKIE * @param {string} EXPIRE_DAYS * @returns {boolean} */ public consent(isConsent: boolean, e: any, COOKIE: string, EXPIRE_DAYS: number) { if (!isConsent) { return this.isConsented; } else if (isConsent) { this.setCookie(COOKIE, ''1'', EXPIRE_DAYS); this.isConsented = true; e.preventDefault(); } } }

He estado buscando cookies angulares por todas partes, pero no he podido encontrar cómo implementar la administración de cookies en Angular. ¿Hay alguna forma de administrar las cookies (como $ cookie en AngularJS)?


Para leer una cookie, he realizado pequeñas modificaciones en la versión de Miquel que no funciona para mí:

getCookie(name: string) { let ca: Array<string> = document.cookie.split('';''); let cookieName = name + "="; let c: string; for (let i: number = 0; i < ca.length; i += 1) { if (ca[i].indexOf(name, 0) > -1) { c = ca[i].substring(cookieName.length +1, ca[i].length); console.log("valore cookie: " + c); return c; } } return "";


Sí, aquí hay una ng2-cookies

Uso:

import { Cookie } from ''ng2-cookies/ng2-cookies''; Cookie.setCookie(''cookieName'', ''cookieValue''); Cookie.setCookie(''cookieName'', ''cookieValue'', 10 /*days from now*/); Cookie.setCookie(''cookieName'', ''cookieValue'', 10, ''/myapp/'', ''mydomain.com''); let myCookie = Cookie.getCookie(''cookieName''); Cookie.deleteCookie(''cookieName'');


También es beneficioso almacenar datos en sessionStorage

// Save data to sessionStorage sessionStorage.setItem(''key'', ''value''); // Get saved data from sessionStorage var data = sessionStorage.getItem(''key''); // Remove saved data from sessionStorage sessionStorage.removeItem(''key''); // Remove all saved data from sessionStorage sessionStorage.clear();

para más detalles https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage


Terminé creando mis propias funciones:

@Component({ selector: ''cookie-consent'', template: cookieconsent_html, styles: [cookieconsent_css] }) export class CookieConsent { private isConsented: boolean = false; constructor() { this.isConsented = this.getCookie(COOKIE_CONSENT) === ''1''; } private getCookie(name: string) { let ca: Array<string> = document.cookie.split('';''); let caLen: number = ca.length; let cookieName = `${name}=`; let c: string; for (let i: number = 0; i < caLen; i += 1) { c = ca[i].replace(/^/s+/g, ''''); if (c.indexOf(cookieName) == 0) { return c.substring(cookieName.length, c.length); } } return ''''; } private deleteCookie(name) { this.setCookie(name, '''', -1); } private setCookie(name: string, value: string, expireDays: number, path: string = '''') { let d:Date = new Date(); d.setTime(d.getTime() + expireDays * 24 * 60 * 60 * 1000); let expires:string = `expires=${d.toUTCString()}`; let cpath:string = path ? `; path=${path}` : ''''; document.cookie = `${name}=${value}; ${expires}${cpath}`; } private consent(isConsent: boolean, e: any) { if (!isConsent) { return this.isConsented; } else if (isConsent) { this.setCookie(COOKIE_CONSENT, ''1'', COOKIE_CONSENT_EXPIRE_DAYS); this.isConsented = true; e.preventDefault(); } } }


Utilice el servicio de cookies NGX

Inastall este paquete: npm install ngx-cookie-service --save

Agregue el servicio de cookies a su app.module.ts como proveedor:

import { CookieService } from ''ngx-cookie-service''; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, ... ], providers: [ CookieService ], bootstrap: [ AppComponent ] })

Luego llame a su componente:

import { CookieService } from ''ngx-cookie-service''; constructor( private cookieService: CookieService ) { } ngOnInit(): void { this.cookieService.set( ''name'', ''Test Cookie'' ); // To Set Cookie this.cookieValue = this.cookieService.get(''name''); // To Get Cookie }

¡Eso es!


Actualización: angular2-cookie ahora está en desuso. Por favor utiliza ngx-cookie lugar.

Vieja respuesta:

Aquí está angular2-cookie que es la implementación exacta del servicio de $cookies Angular 1 $cookies (más un método removeAll() ). Utiliza los mismos métodos, solo implementado en mecanografiado con lógica Angular 2.

Puede inyectarlo como un servicio en la matriz de providers componentes:

import {CookieService} from ''angular2-cookie/core''; @Component({ selector: ''my-very-cool-app'', template: ''<h1>My Angular2 App with Cookies</h1>'', providers: [CookieService] })

Después de eso, defínalo en el consturctur como de costumbre y comience a usar:

export class AppComponent { constructor(private _cookieService:CookieService){} getCookie(key: string){ return this._cookieService.get(key); } }

Puede obtenerlo a través de npm:

npm install angular2-cookie --save