Angular2 cookie而不是localstorage [英] Angular2 cookies instead of localstorage

查看:194
本文介绍了Angular2 cookie而不是localstorage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设法让所有工作JWT认证,没有问题,但它只支持现代浏览器,我需要Auth从IE9及以上开始全部工作。

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.

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

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.

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

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


推荐答案

解决此问题的一种简单方法是使用此lib:

A simple way to solve this is use this lib:

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

要安装此库,请运行:

To install this library, run:

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

这篇关于Angular2 cookie而不是localstorage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆