Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import { Injectable } from '@angular/core'
/** provides a caching service, with a key, the data and a timeout ()
Warning: Objects are stored as json-Strings. I.e. Dates objects (and others) may not be converted correctly */
@Injectable()
export class CacheService {
constructor() { }
save(options: LocalStorageSaveOptions) {
// Set default values for optionals
options.expirationMins = options.expirationMins || 0
// Set expiration date in miliseconds
const expirationMS = options.expirationMins !== 0 ? options.expirationMins * 60 * 1000 : 0
const record = {
value: typeof options.data === 'string' ? options.data : JSON.stringify(options.data),
expiration: expirationMS !== 0 ? new Date().getTime() + expirationMS : null,
hasExpiration: expirationMS !== 0 ? true : false
}
localStorage.setItem(options.key, JSON.stringify(record))
}
load(key: string) {
// Get cached data from localstorage
const item = localStorage.getItem(key)
if (item !== null) {
const record = JSON.parse(item)
const now = new Date().getTime()
// Expired data will return null
if (!record || (record.hasExpiration && record.expiration <= now)) {
return null
} else {
return JSON.parse(record.value)
}
}
return null
}
remove(key: string) {
localStorage.removeItem(key)
}
cleanLocalStorage() {
localStorage.clear()
}
}
export class LocalStorageSaveOptions {
key = '';
data: any
expirationMins?: number
}