Last active
January 3, 2019 14:11
-
-
Save reymon359/30094553042012756527ee3055dd9dae to your computer and use it in GitHub Desktop.
A string variable local storage provider for ionic. ( Done a bit too fast, probably something worng)
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
// Author: Ramon Morcillo @reymon359 | |
import { Platform } from "ionic-angular"; | |
import { Storage } from "@ionic/storage"; | |
@Injectable() | |
export class StorageProvider { | |
constructor(private platform: Platform, private storage: Storage) { | |
console.log('Hello Storage Provider'); | |
} | |
// --------------- STRINGS------------------- | |
save(something:string) { | |
if (this.platform.is("cordova")) { | |
// Mobile | |
this.storage.set('something', something); | |
} else { | |
// PC | |
localStorage.setItem('something', something); | |
} | |
} | |
load(something:string) { | |
let promise = new Promise((resolve, reject) => { | |
if (this.platform.is("cordova")) { | |
// Mobile | |
this.storage.ready() | |
.then(() => { | |
this.storage.get(something) | |
.then(something => { | |
if (something) { | |
resolve(something); | |
} | |
else { | |
reject(new Error(something + "could not be loaded ")); | |
} | |
}) | |
}) | |
} else { | |
// PC | |
if (localStorage.getItem(something)) { | |
resolve(localStorage.getItem(something)); | |
} else { | |
reject(new Error(something + "could not be loaded ")); | |
} | |
} | |
}); | |
return promise; | |
} | |
// --------------- OBJECTS------------------- | |
// The ionic storage lets you storage objects but if you are in | |
// Pc you have to parse them to string to store them. And then parse | |
// them to json to load . | |
saveObject(object) { | |
if (this.platform.is("cordova")) { | |
// Mobile | |
this.storage.set('objectName', object); | |
} else { | |
// PC | |
let objectToSave = JSON.stringify(object); | |
localStorage.setItem('objectName', objectToSave); | |
} | |
} | |
load(objectName:string) { | |
let promise = new Promise((resolve, reject) => { | |
if (this.platform.is("cordova")) { | |
// Mobile | |
this.storage.ready() | |
.then(() => { | |
this.storage.get(objectName) | |
.then(object => { | |
if (object) { | |
resolve(object); | |
} | |
else { | |
reject(new Error(objectName + "could not be loaded ")); | |
} | |
}) | |
}) | |
} else { | |
// PC | |
if (localStorage.getItem(objectName)) { | |
let objectToLoad = JSON.parse(window.localStorage.getItem(objectName)); | |
resolve(objectToLoad); | |
} else { | |
reject(new Error(objectName + "could not be loaded ")); | |
} | |
} | |
}); | |
return promise; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment