Angular 4中ngx-cookie-service存的转义Cookie转JSON问题
嘿,我之前也碰到过一模一样的情况!问题根源在于双重编码:ngx-cookie-service的set方法默认会自动对传入的值做URL编码,而你又先手动做了JSON.stringify,等于最终存的是「JSON字符串的URL编码结果」。当你用get方法取的时候,它只会帮你解码一次,拿到的还是经过URL编码的JSON串,直接JSON.parse肯定报错。
两种解决办法任你选:
办法一:获取时手动解码再解析
先把取到的字符串做一次URL解码,再用JSON.parse转成对象,代码如下:
// 从Cookie拿值 const encodedCookie = cookieService.get('merchant_data'); // 先解码URL编码的内容 const decodedCookie = decodeURIComponent(encodedCookie); // 解析成原始JSON对象 const merchantData = JSON.parse(decodedCookie); // 现在就能正常用啦 console.log(merchantData.merchant_name); console.log(merchantData.role);
办法二:存储时关闭自动编码
如果你不想每次取的时候都手动解码,可以在存Cookie的时候,把ngx-cookie-service的自动编码关掉(set方法的第六个参数设为false):
let defaultData = { merchant_name : response.data.profile.business_name, role : response.data.role, id : response.data.merchant_id, is_default : false }; let cookieData = JSON.stringify(defaultData); // 最后一个参数设为false,关闭自动URL编码 cookieService.set('merchant_data', cookieData, undefined, undefined, undefined, false);
这样之后直接用JSON.parse(cookieService.get('merchant_data'))就能得到原始对象了。
小提醒:关闭自动编码后,要确保你的JSON字符串里没有Cookie不允许的特殊字符(比如空格、分号这类),如果有特殊字符,还是建议用第一种办法,保留自动编码更稳妥。
内容的提问来源于stack exchange,提问作者Vikram
相关产品推荐
相关产品推荐

