有angular的cookies

我一直在寻找angular落的cookies,但我一直没有find如何在Angular中实施cookiespipe理。 有什么办法来pipe理cookie(如AngularJS中的$ cookie )?

我结束了创build自己的function:

@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(); } } } 

这里是angular2-cookie ,它是Angular 1 $cookies服务(加上removeAll()方法)的确切实现。 它使用的是相同的方法,只能在使用Angular 2逻辑的打字稿中实现。

您可以将其作为服务注入组件providers数组中:

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

之后,像往常一样在consturctur中定义它,并开始使用:

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

你可以通过npm得到它:

 npm install angular2-cookie --save 

是的,这里有一个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'); 

为了阅读一个cookie,我对Miquel版本进行了一些修改,这些修改对我不起作用:

 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 "";