我一直在寻找Angular cookies,但我还没有找到如何在Angular中实现cookie管理.有没有办法管理cookie(比如AngularJS中的$ cookie)?
我结束了创建自己的功能:
@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= 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(); } } }
这是angular2-cookie,它是Angular 1 $cookies
服务的精确实现(加上一个removeAll()
方法).它使用相同的方法,仅在带有Angular 2逻辑的打字稿中实现.
您可以将其作为服务注入组件providers
数组中:
import {CookieService} from 'angular2-cookie/core'; @Component({ selector: 'my-very-cool-app', template: 'My Angular2 App with Cookies
', providers: [CookieService] })
之后,像往常一样在consturctur中定义它并开始使用:
export class AppComponent { constructor(private _cookieService:CookieService){} getCookie(key: string){ return this._cookieService.get(key); } }
你可以通过npm得到它:
npm install angular2-cookie --save
编辑:angular2-cookie现已弃用.请改用ngx-cookie.
是的,这是一个ng2-cookies
用法:
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');