Created
November 20, 2017 11:14
-
-
Save smorcuend/0b42cf83788b2d4650a9558c31fa9b87 to your computer and use it in GitHub Desktop.
Settings provider example ionic
This file contains hidden or 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
import { Injectable } from '@angular/core'; | |
import { Http } from '@angular/http'; | |
import 'rxjs/add/operator/map'; | |
import { Observable } from 'rxjs/Observable' | |
import 'rxjs/add/observable/of'; | |
import { Storage } from '@ionic/storage'; | |
export class AppSettings { | |
website_host: string = null; | |
website_port: number = null; | |
} | |
@Injectable() | |
export class SettingsProvider { | |
settings: AppSettings; | |
constructor(private http: Http, private storage: Storage) { } | |
public set(settingName, value) { | |
return this.storage.set(`setting:${settingName}`, value); | |
} | |
public async get(settingName) { | |
return await this.storage.get(`setting:${settingName}`); | |
} | |
public async remove(settingName) { | |
return await this.storage.remove(`setting:${settingName}`); | |
} | |
public clear() { | |
this.storage.clear().then(() => { | |
console.log('Storage cleared'); | |
}); | |
} | |
loadSettings(): Promise<boolean> { | |
return new Promise((resolve, reject) => { | |
var getPromises = []; | |
this.storage.ready().then(() => { | |
this.settings = new AppSettings(); | |
for (var settingName in this.settings) { | |
getPromises.push(this.storage.get(settingName).then((val) => { (this.settings[settingName] = val); })); | |
} | |
Promise.all(getPromises).then((data) => { | |
console.debug("Settings loaded", this.settings); | |
resolve(true); | |
}); | |
}) | |
.catch((error) => { | |
console.log('Error loading settings from storage', error); | |
}); | |
}); | |
} | |
getSettings(): Promise<AppSettings> { | |
return new Promise((resolve, reject) => { | |
this.loadSettings().then(() => { | |
resolve(this.settings); | |
}); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment