javascript - Angular cookies
我一直在四處尋找 Angular 的 cookies,但我無法找到如何在 Angular 中實現 cookies 管理。有沒有辦法管理 cookies(像在 AngularJS 中的 $cookie)?
答案#1
我最後創建了自己的函數:
@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();
}
}
}
答案#2
更新: angular2-cookie 現在已被棄用。請改用我的 ngx-cookie。
舊答案: :
這裡是 angular2-cookie,它是我創建的 Angular 1 $cookies 服務的完整實現(另外增加了一個 removeAll() 方法)。它使用相同的方法,只是用 Angular 2 邏輯以 TypeScript 實現。
你可以將它注入為元件中 providers 陣列的服務:
import {CookieService} from 'angular2-cookie/core';
@Component({
selector: 'my-very-cool-app',
template: '<h1>My Angular2 App with Cookies</h1>',
providers: [CookieService]
})
之後,像平常一樣在建構函式中定義它,並開始使用:
export class AppComponent {
constructor(private _cookieService:CookieService){}
getCookie(key: string){
return this._cookieService.get(key);
}
}
你可以透過 npm 取得它:
npm install angular2-cookie --save
答案#3
使用 NGX Cookie Service
安裝此套件:npm install ngx-cookie-service --save
將 Cookie 服務作為提供者添加到你的 app.module.ts 中:
import { CookieService } from 'ngx-cookie-service';
@NgModule({
declarations: [ AppComponent ],
imports: [ BrowserModule, ... ],
providers: [ CookieService ],
bootstrap: [ AppComponent ]
})
然後調用你的組件:
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
}
就這樣!
答案#4
是的,這裡有一個 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');
