2015-11-03 65 views
13

我设法使所有工作JWT授权,没有问题,但它只支持现代浏览器,我需要从IE9开始,所有工作都从IE9开始。Angular2饼干代替本地存储

我找不到任何信息或示例如何在Angular2中使用cookie。有一个简单的例子使用localStorage来保存令牌,我需要相同的功能,但使用cookies来完成。

任何帮助将是伟大的,因为网上没有任何东西。

this.http.post("http://localhost:3001/sessions/create", creds, { headers: header }) 
    .map(res => res.json()) 
    .subscribe(
     data => localStorage.setItem('id_token',data.id_token), 
     err => this.logError(err), 
    () => console.log("Auth is completed!") 
    ); 

回答

23

一个简单的方法来解决,这是使用此lib目录下:

https://www.npmjs.com/package/ng2-cookies

要安装此库,运行:

$ npm install ng2-cookies 

用法:

import { Cookie } from 'ng2-cookies/ng2-cookies'; 

Cookie.set('cookieName', 'cookieValue'); 
Cookie.set('cookieName', 'cookieValue', 10 /*days from now*/); 
Cookie.set('cookieName', 'cookieValue', 10, '/myapp/', 'mydomain.com'); 

let myCookie = Cookie.get('cookieName'); 

/* 
* List of cookies as Object, like: { cookieName: "cookieValue", cookieName2: "cookieValue2" ... etc } 
*/ 
let cookielist = Cookie.getAll(); 

Cookie.delete('cookieName'); 
Cookie.deleteAll(); 
+2

虽然这在理论上可以回答的问题,[这将是优选的](// meta.stackoverflow.com/q/8259 )在这里包括答案的基本部分,并提供参考链接。 –

4

我执行将角色1到角色2的功能作为可注射的服务授予cookie服务。此外还添加了removeAll函数。

npm install angular2-cookie --save 

注入它作为一个服务后,您可以使用这些方法在角1:你可以把它

this._cookieService.get(key); 
this._cookieService.getObject(key); 
// Other available methods are 
// put(), putObject(), remove() and removeAll() 

您可以检查例子和可用功能自述部分。

https://github.com/salemdar/angular2-cookie

0

对于角首轮npm命令npm install angular2-cookie --save使用的cookie,
注入在app.module.ts服务后添加

import { CookieService } from 'angular2-cookie/services/cookies.service'; 

或供应商添加服务,

providers: [CookieService] 

向你的c添加一个cookie后您使用的组件 有7种方法用于Cookie
1.)get():- This method returns the value of given cookie key.
2.)getObject() :- This method is returns the desterilized value of given cookie key
3.)get all():- This method returns a key-value object with all the cookies.
4.)put():- This method is used to set a value for given cookie key.
5.)putObject():- This method is used to serializes and set a value for given cookie key.
6.)remove(): -This method is used to remove given cookie
7)remove all(): -This method is used to remove all cookies.

认沽/在设置cookie值:this._cookieService.put('key:string', 'value:string');这里的关键是你的cookie名称例如:user1和值是集any value

用于在cookie GET值:this._cookieService.get('key');

用于从组分中除去的cookie然后this._cookieService.remove('key');