当我尝试使用setItem在localstorage中设置数据并使用getItem获取数据时,一切都在chrome和firefox中正常工作,但在IE或Edge中无效。
在Edge中收到这些错误。
未捕获(承诺):错误:参数无效
无效参数Storageservice.prototype.setItem
未处理的承诺拒绝:无效的参数。,zone:angular; 任务:promise.then; value:错误:argument.error无效:无效 参数。
在IE中:
EXCEPTION:未捕获(承诺):QuotaExceededError ORIGINAL STACKTRACE:错误:未捕获(在承诺中):QuotaExceededError
未处理的Promise拒绝:QuotaExceededError;区域:角; 任务:Promise.then;值:QuotaExceededError undefined
我正在使用以下代码段 -
setItem(key: string, data: any, storageType: string = 'localStorage'): any {
let _storage: any = localStorage;
if (storageType !== 'localStorage') {
//sessionStorage maybe?
_storage = sessionStorage;
}
let _data = this.transform('set', (typeof data === "string") ? data : JSON.stringify(data));
_storage.setItem(key, _data);
}
/**
* getItem(key) returns the cache object from storage
*/
getItem(key: string, ifNotFound: any = {}, storageType: string = 'localStorage'): any {
let _storage: any = localStorage;
if (storageType !== 'localStorage') {
//sessionStorage maybe?
_storage = sessionStorage;
}
let _data = _storage.getItem(key);
if (_data) {
try {
return JSON.parse(this.transform('get', _data));
} catch (e) {
return ifNotFound;
}
}
return ifNotFound;
}
/**
* transform() returns the object transformed to storage
*/
transform(type: string = 'set', data: any): any {
var isMSIE = (/trident/i).test(navigator.userAgent);
if (isMSIE) {
return data;
} else {
if (type === 'set') {
//compress the data to Base64 and then do unicode encoding
return LZString.compress(data);
/*return this.encodeModal.encoder.compress(data);*/
} else {
//transform for fetch
return LZString.decompress(data);
//return this.encodeModal.encoder.decompress(data);
}
}
}