Javascript Angular2 cookie 而不是 localstorage

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33495635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:08:52  来源:igfitidea点击:

Angular2 cookies instead of localstorage

javascripthtmlcookiesangular

提问by Milan Milanovic

I managed to make all work JWT auth, no problems there, but it only supports modern browsers, and I need Auth to work in all starting from IE9 and upwards.

我设法使所有工作都通过 JWT 身份验证,那里没有问题,但它仅支持现代浏览器,并且我需要 Auth 才能从 IE9 及更高版本开始工作。

I could not find any info or examples how to use cookies in Angular2. There is a simple example using localStorage for saving token, I need the same functionality but done with cookies.

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

Any help would be great, since there isn't anything on this on the net.

任何帮助都会很棒,因为网络上没有任何内容。

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

回答by Exdcarca

A simple way to solve this is use this lib:

解决这个问题的一个简单方法是使用这个库:

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

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

To install this library, run:

要安装此库,请运行:

$ npm install ng2-cookies

Usage:

用法:

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

回答by s.alem

I implemented the cookie service with the functions from Angular 1 to the Angular 2 as an injectable service. Also added a removeAllfunction as a plus. You can get it with:

我使用从 Angular 1 到 Angular 2 的功能实现了 cookie 服务作为可注入服务。还添加了一个removeAll功能作为加号。您可以通过以下方式获取:

npm install angular2-cookie --save

After injecting it as a service, you can use the methods as in Angular 1:

将其作为服务注入后,您可以使用 Angular 1 中的方法:

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

You can check the readme part for examples and available functions.

您可以查看自述部分以获取示例和可用功能。

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

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

回答by Brijesh Mavani

For use cookie in angular first run npmcommand npm install angular2-cookie --save,
After injecting your service in app.module.tsadd

对于角第一次运行时使用的cookienpm命令npm install angular2-cookie --save
在注入你的服务后,app.module.ts

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

or add service in provider,

或在提供者中添加服务,

 providers: [CookieService]

after adding a cookie to your component where you used there are 7 methods for cookies
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 添加到您使用的组件后,有 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.

for put/set value in a cookie :this._cookieService.put('key:string', 'value:string');here key as your cookie name ex:user1and value is for set any value.

for get value in a cookie:this._cookieService.get('key');

for remove cookie from component then this._cookieService.remove('key');

用于放置/设置 cookie 中的值:this._cookieService.put('key:string', 'value:string');此处键为您的 cookie 名称 ex:user1值用于 set any value

获取 cookie 中的值:this._cookieService.get('key');

用于从组件中删除 cookie 然后this._cookieService.remove('key');