Skip to content

Instantly share code, notes, and snippets.

@kmassada
Created April 5, 2016 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmassada/008be87363d31efe25f9add426b1e322 to your computer and use it in GitHub Desktop.
Save kmassada/008be87363d31efe25f9add426b1e322 to your computer and use it in GitHub Desktop.
TypeScript Angular Factory
export interface IStorageService {
set(key: string, value: any): void;
remove(key: string): void;
get(key: string, defaultValue: any): any;
setObject(key: string, value: any): void;
getObject(key: string): any;
removeObject (key: string): void;
}
class StorageService implements IStorageService {
private storage: any;
constructor(private $window: angular.IWindowService) {
this.storage = this.storage;
}
set(key: string, value: any) {
this.storage[key] = value;
};
get(key: string, defaultValue: any) {
return this.storage[key] || defaultValue;
};
remove(key: string) {
this.storage.removeItem(key);
};
setObject(key: string, value: any) {
this.storage[key] = JSON.stringify(value);
};
getObject(key: string) {
return JSON.parse(this.storage[key] || "{}");
};
removeObject(key: string) {
this.remove(key);
};
}
factory.$inject = ["$window"];
function factory($window: angular.IWindowService): IStorageService {
return new StorageService($window);
}
angular
.module("Services.StorageService", [])
.factory("storageService", factory);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment