Created
January 13, 2020 15:55
-
-
Save Tazaf/41dead0b923c1396e96e98a76dd9bd18 to your computer and use it in GitHub Desktop.
Simple cache service base class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Extends this class to make any class a temporary-cache-like class. | |
* | |
* Especially useful for Angular services, so that you can store any value in it from _e.g._ a component, | |
* and retrieve this stored value from another component. | |
* | |
* This is a generic class to which you can specify the type of data that this cache should accept. | |
*/ | |
export class CacheService<T> { | |
private cache: T; | |
/** | |
* Set the cache value | |
* @param cache The value to cache | |
*/ | |
setCache(cache: T) { | |
this.cache = cache; | |
} | |
/** | |
* Get the previously cached value and empty the current cache | |
*/ | |
getCache(): T { | |
const cache = this.cache; | |
this.cache = null; | |
return cache; | |
} | |
/** | |
* Checks if there's a value in the cache | |
*/ | |
hasCache(): boolean { | |
return Boolean(this.cache); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment