Ionic2 data storage
translation 2017-03-29 14:50:51
When in a native app lexical environment, SQLite is generally preferred because it is one of the most widely used and stable document databases, and it also avoids some Dilemmas such as localstorage and IndexedDB, such as the system flushing data when it runs out of disk space.
If you are running on the web or web app, you generally tend to use IndexedDB, WebSQL, and localstorage.
If you are using SQLite, first you have to install the cordova-sqlite-storage plugin.
cordova plugin add cordova-sqlite-storage --save
1
Then npm follow the package:
npm install --save @ionic/storage
1
After importing the plugin, inject the module into the app in your NgModule's imports array.
Here is an example:
import { IonicStorageModule } from '@ionic/storage';
@NgModule({
declarations: [
// ...
],
imports: [
IonicModule.forRoot(MyApp),
IonicStorageModule.forRoot() //This is it
],
bootstrap: [IonicApp],
entryComponents: [
// ...
],
providers: []
})
export class AppModule {}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 In
this way, if you need to use the database in that component, you can inject it through import:
import { Storage } from '@ionic/storage';
export class MyApp {
constructor(storage: Storage) {
storage.ready().then(() => {
// set a key/value
storage.set('name', 'Max');
// Or to get a key/value pair
storage.get('age' ).then((val) => {
console.log('Your age is', val);
})
});
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Configuration Storage
Development The user can configure the storage engine with the defined storage engine priority, or customize the configuration options to localForage.
Note: Any custom configuration will be merged into the default configuration.
import { IonicStorageModule } from '@ionic/storage';
@NgModule({
declarations: ...,
imports: [
IonicStorageModule.forRoot({
name: '__mydb',
driverOrder: ['indexeddb', 'sqlite', 'websql' ]
})
],
bootstrap: ...,
entryComponents: ...,
providers: []
})
export class AppModule {}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Here is how the database is used:
driver get driver name
ready() response storage
get(key) get corresponding data
set(key, value) set data
remove(key) delete corresponding data
clear() clear all data
length() get data length
keys() get key
forEach( callback) traverse the database
Data storage for Ionic2
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=326043129&siteId=291194637
Recommended
Ranking