I'm using ionic-native SQLite database for Ionic application and for testing in browser i'm using WebSQL.
It's all working fine in browser, but when running application in android devices. it gives me error like Cannot read property 'transaction' of undefined.
Below is code for reference.
1) DBProvider.ts
import { Platform } from 'ionic-angular';
import { Injectable } from '#angular/core';
import { SQLite, SQLiteObject } from '#ionic-native/sqlite';
declare var window: any;
#Injectable()
export class DBProvider {
DB_NAME: string = 'DailySheet.db';
public websql = null;
public sqlite: SQLite;
sqliteobj: any;
public AppUsers = [];
constructor(public platform: Platform) {
if (this.platform.is('core')) {
this.websql = window.openDatabase(this.DB_NAME, "1.0", "Test DB", 2 * 1024 * 1024);
console.log('Database opened.');
this.createTable();
}
this.platform.ready().then(() => {
if (!this.platform.is('core')) {
this.sqlite.create({ name: this.DB_NAME, location: 'default' })
.then((db: SQLiteObject) => {
console.log('Database opened.');
this.sqliteobj = db;
this.createTable();
});
}
});
}
createTable() {
this.query(`CREATE TABLE IF NOT EXISTS AppUser (
UserId INTEGER NOT NULL,
MobileNo TEXT NOT NULL UNIQUE,
Email TEXT,
PRIMARY KEY(UserId)
)`)
.then(data => {
console.log('Table created.');
})
.catch(err => {
console.error('Unable to create initial storage tables', err.tx, err.err);
});
}
getAppUsers(): Promise<any> {
let query = 'SELECT * FROM AppUser';
return this.query(query)
.then(data => {
if (data.res.rows.length > 0) {
console.log('Rows found.');
return data.res.rows;
}
else {
console.log('No rows found.');
}
});
}
insertAppUser(): Promise<any> {
let id = 1;
let mobileno = '8905606191';
let email = 'niravparsana94#gmail.com';
return this.query('INSERT INTO AppUser (UserId, MobileNo, Email) VALUES (' + id + ' ,\"' + mobileno + '\" ,\"' + email + '\")')
.then(data => {
console.log('Insert success.');
return data;
})
.catch(err => {
console.error('Unable to insert', err.tx, err.err);
});
}
updateAppUser(UserId): Promise<any> {
let query = "UPDATE Todo SET Email=? WHERE UserId=?";
return this.query(query, ['niravparsana#outlook.com', UserId])
.then(data => {
console.log('AppUser Updated.');
return data;
})
.catch(err => {
console.error('Unable to update', err.tx, err.err);
});
}
deleteAppUser(UserId): Promise<any> {
let query = "DELETE FROM AppUser WHERE UserId=?";
return this.query(query, [UserId])
.then(data => {
return data;
})
.catch(err => {
console.error('Unable to delete', err.tx, err.err);
});
}
query(query: string, params: any[] = []): Promise<any> {
return new Promise((resolve, reject) => {
try {
if (this.platform.is('core')) {
this.websql.transaction((tx: any) => {
tx.executeSql(query, params,
(tx: any, res: any) => resolve({ tx: tx, res: res }),
(tx: any, err: any) => reject({ tx: tx, err: err }));
},
(err: any) => reject({ err: err }));
}
else {
this.sqliteobj.transaction((tx: any) => {
tx.executeSql(query, params,
(tx: any, res: any) => resolve({ tx: tx, res: res }),
(tx: any, err: any) => reject({ tx: tx, err: err }));
},
(err: any) => reject({ err: err }));
}
} catch (err) {
reject({ err: err });
}
});
}
}
2) home.ts
import { Component, OnInit } from '#angular/core';
import { NavController, Platform } from 'ionic-angular';
import { DBProvider } from '../../providers/DBProvider';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage implements OnInit {
AppUsers: Array<Object>;
constructor(public navCtrl: NavController, private platform: Platform, public db: DBProvider) {
}
ionViewDidLoad() {
this.deleteAppUser();
this.insertAppUser();
this.getAllAppUsers();
}
ngOnInit() {
}
public deleteAppUser() {
this.db.deleteAppUser(1)
.then(data => {
if (data.res.rowsAffected == 1) {
console.log('AppUser Deleted.');
}
else {
console.log('No AppUser Deleted.');
}
})
.catch(ex => {
console.log(ex);
});
}
public insertAppUser() {
this.db.insertAppUser()
.then(data => {
})
.catch(ex => {
console.log(ex);
});
}
public getAllAppUsers() {
this.db.getAppUsers()
.then(data => {
this.AppUsers = data;
})
.catch(ex => {
console.log(ex);
});
}
}
While debugging, I figured out somewhat that code runs in difference sequence in browser and mobile.
In browser
DBProvider constructor
this.CreateTable() function(DBProvider.ts)
this.deleteAppUser() function(home.ts)
this.insertAppUser() function(home.ts)
this.getAllAppUsers() function(home.ts)
In Android device
DBProvider constructor
this.deleteAppUser() function(home.ts)
this.insertAppUser() function(home.ts)
this.getAllAppUsers() function(home.ts)
this.CreateTable() function(DBProvider.ts)
As you can this.sqliteobj is assigned in DBProvider constructor. but while debug i found that funtions from home.ts are calling before this.sqliteobj get assigned, that's why it gives an error like Cannot read property 'transaction' of undefined. But then question is why functions from home.ts getting called before this.sqliteobj get assigned?
To my knowledge you need this.sqlite.create(... in every call on the sqlite database. So you have to include it in your query function before the sqliteobj.
Related
Hello I am trying to make an API Post request using Firebase cloud function,Here are the code.
My effort is to get details from cloud and make an http request to my project's API. But i am getting an error of can not find module!!i have already put it.
so how to make an api call??
Here is my index.ts
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import {TenantServiceProxy, CreateTenantInput} from '../../src/app/cloud/cloud-service';
let _tenantService: TenantServiceProxy;
const tenant = new CreateTenantInput();
admin.initializeApp();
export const onOrganizationUpdate =
functions.firestore.document('organizations/{id}').onUpdate(change => {
const after = change.after.data()
const payload = {
data: {
OrganizationId: String(after.OrganizationId),
Name: String(after.Name),
IsDeleted: String(after.IsDeleted)
}
}
console.log("updated", payload);
https.get('https://reqres.in/api/users?page=2', (resp: any) => {
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk: any) => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
console.log("-------------------->",JSON.parse(data));
});
}).on("error", (err: any) => {
console.log("Error: " + err.message);
});
return admin.messaging().sendToTopic("OrganizationId", payload)
})
export const onOrganizationCreate =
functions.firestore.document('organizations/{id}').onCreate(change=>{
const onCreationTime =change.data()
const payload={
data:{
organizationId:String(onCreationTime.organizationId),
name:String(onCreationTime.name),
isDeleted:String(onCreationTime.isDeleted)
},
}
console.log("created",payload);
tenant.pkOrganization = payload.data.organizationId;
tenant.name = payload.data.name;
tenant.isDeleted = Boolean(payload.data.isDeleted);
_tenantService.createTenant(tenant).subscribe(()=>{
console.log("created",payload);
});
return admin.messaging().sendToTopic("OrganizationId",payload)
})
Here is the cloud.service.module.TS
//cloud service module
import { AbpHttpInterceptor } from '#abp/abpHttpInterceptor';
import { HTTP_INTERCEPTORS } from '#angular/common/http';
import { NgModule } from '#angular/core';
import * as ApiServiceProxies from '../../app/cloud/cloud-service';
#NgModule({
providers: [
ApiServiceProxies.TenantServiceProxy,
{ provide: HTTP_INTERCEPTORS, useClass: AbpHttpInterceptor, multi: true }
]
})
export class CloudServiceModule { }
Here is My api call service
#Injectable()
export class TenantServiceProxy {
private http: HttpClient;
private baseUrl: string;
protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;
constructor(#Inject(HttpClient) http: HttpClient, #Optional() #Inject(API_BASE_URL) baseUrl?: string) {
this.http = http;
this.baseUrl = baseUrl ? baseUrl : '';
}
createTenant(input: CreateTenantInput | null | undefined): Observable<void> {
let url_ = this.baseUrl + '/api/services/app/Tenant/CreateTenant';
url_ = url_.replace(/[?&]$/, '');
const content_ = JSON.stringify(input);
const options_: any = {
body: content_,
observe: 'response',
responseType: 'blob',
headers: new HttpHeaders({
'Content-Type': 'application/json',
})
};
return this.http.request('post', url_, options_).pipe(_observableMergeMap((response_: any) => {
return this.processCreateTenant(response_);
})).pipe(_observableCatch((response_: any) => {
if (response_ instanceof HttpResponseBase) {
try {
return this.processCreateTenant(<any>response_);
} catch (e) {
return <Observable<void>><any>_observableThrow(e);
}
} else {
return <Observable<void>><any>_observableThrow(response_);
}
}));
}
protected processCreateTenant(response: HttpResponseBase): Observable<void> {
const status = response.status;
const responseBlob =
response instanceof HttpResponse ? response.body :
(<any>response).error instanceof Blob ? (<any>response).error : undefined;
const _headers: any = {}; if (response.headers) { for (const key of response.headers.keys()) { _headers[key] = response.headers.get(key); } }
if (status === 200) {
return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
return _observableOf<void>(<any>null);
}));
} else if (status !== 200 && status !== 204) {
return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
return throwException('An unexpected server error occurred.', status, _responseText, _headers);
}));
}
return _observableOf<void>(<any>null);
}
}
I have defined the module in my services.
I have the following controller action
[HttpPost]
[Route("api/Tenant/SetTenantActive")]
public async Task<IHttpActionResult> SetTenantActive(string tenantid)
{
var tenantStore = CosmosStoreFactory.CreateForEntity<Tenant>();
var allTenants = await tenantStore.Query().Where(x => x.TenantDomainUrl != null).ToListAsync();
foreach(Tenant ten in allTenants)
{
ten.Active = false;
await tenantStore.UpdateAsync(ten);
}
var tenant = await tenantStore.Query().FirstOrDefaultAsync(x => x.Id == tenantid);
if (tenant == null)
{
return NotFound();
}
tenant.Active = true;
var result = await tenantStore.UpdateAsync(tenant);
return Ok(result);
}
And my react code:
import React, { Component } from 'react';
import { Table, Radio} from 'antd';
import { adalApiFetch } from '../../adalConfig';
import Notification from '../../components/notification';
class ListTenants extends Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
fetchData = () => {
adalApiFetch(fetch, "/Tenant", {})
.then(response => response.json())
.then(responseJson => {
if (!this.isCancelled) {
const results= responseJson.map(row => ({
key: row.ClientId,
ClientId: row.ClientId,
ClientSecret: row.ClientSecret,
Id: row.Id,
SiteCollectionTestUrl: row.SiteCollectionTestUrl,
TenantDomainUrl: row.TenantDomainUrl
}))
this.setState({ data: results });
}
})
.catch(error => {
console.error(error);
});
};
componentDidMount(){
this.fetchData();
}
render() {
const columns = [
{
title: 'Client Id',
dataIndex: 'ClientId',
key: 'ClientId'
},
{
title: 'Site Collection TestUrl',
dataIndex: 'SiteCollectionTestUrl',
key: 'SiteCollectionTestUrl',
},
{
title: 'Tenant DomainUrl',
dataIndex: 'TenantDomainUrl',
key: 'TenantDomainUrl',
}
];
// rowSelection object indicates the need for row selection
const rowSelection = {
onChange: (selectedRowKeys, selectedRows) => {
if(selectedRows[0].key != undefined){
console.log(selectedRows[0].key);
const options = {
method: 'post',
body: {tenantid:selectedRows[0].key},
};
adalApiFetch(fetch, "/Tenant/SetTenantActive", options)
.then(response =>{
if(response.status === 200){
Notification(
'success',
'Tenant created',
''
);
}else{
throw "error";
}
})
.catch(error => {
Notification(
'error',
'Tenant not created',
error
);
console.error(error);
});
}
},
getCheckboxProps: record => ({
type: Radio
}),
};
return (
<Table rowSelection={rowSelection} columns={columns} dataSource={this.state.data} />
);
}
}
export default ListTenants;
focus only on the onchange event,
And the screenshot:
And it looks like the request gets to the webapi (I attached the debugger)
Update:
Basically If I dont put FromBody I need to send the parameter via querystring.
However if I put from Body and I send the parameter in the body, its received null on the webapi
Add [FromBody] before your input parameter in your action method like this:
public async Task<IHttpActionResult> SetTenantActive([FromBody] string tenantid)
Then, convert your selected row key into string
const options = {
method: 'post',
body: { tenantid : selectedRows[0].key.toString() }
};
I want to create a new user document in my Cloud Firestore database whenever a new user logs in. Each doc should have a unique id and I want a "uid" property for each user to match the unique auto-generated id for the doc. At first, I just always ran an update on the user, but I figured it could be helpful to separate my create and update logic. As you can see I haven't worked out how to query if a user exists, but I figured I should test the createUser function before continuing.
Anyway, while I was testing my createUser function I ran into a compilation error.
ERROR in src/app/services/auth.service.ts(64,22): error TS2554:
Expected 1 arguments, but got 0.
UPDATE:
When I try to run the function from localhost after compilation I get this error in the console.
Function CollectionReference.doc() requires its first argument to be
of type string, but it was: undefined
Here is my proposed solution:
import { Injectable } from '#angular/core';
import { User } from './../models/user.model';
import { PermissionsService } from './permissions.service';
import { auth } from 'firebase/app';
import { AngularFireAuth } from 'angularfire2/auth';
import {
AngularFirestore,
AngularFirestoreDocument,
AngularFirestoreCollection,
} from 'angularfire2/firestore';
import { Observable, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';
#Injectable({
providedIn: 'root',
})
export class AuthService {
usersCollection: AngularFirestoreCollection<User> = null;
user: Observable<User>;
constructor(
private afAuth: AngularFireAuth,
private db: AngularFirestore,
private permissionsService: PermissionsService,
) {
this.usersCollection = db.collection('users');
this.user = this.afAuth.authState.pipe(
switchMap((user) => {
if (user) {
return this.db
.doc<User>(`users/${user.uid}`)
.valueChanges();
} else {
return of(null);
}
}),
);
}
loginGoogle() {
const provider = new auth.GoogleAuthProvider();
return this.oAuthLogin(provider);
}
loginFacebook() {
const provider = new auth.FacebookAuthProvider();
return this.oAuthLogin(provider);
}
loginTwitter() {
const provider = new auth.TwitterAuthProvider();
return this.oAuthLogin(provider);
}
oAuthLogin(provider) {
return this.afAuth.auth.signInWithPopup(provider).then((credential) => {
//if(the user exists already)
//this.updateUserData(credential.user);
//else
this.createUser();
});
}
createUser() {
const newUserRef = this.usersCollection.doc<User>(); // Error here
let newUser: User;
this.user.subscribe((userData) => {
newUser = {
uid: newUserRef.id,
email: userData.email,
photoURL: userData.photoURL,
displayName: userData.displayName,
roles: {
member: true,
},
permissions: this.permissionsService.memberPermissions;
};
});
newUserRef
.set(newUser)
.then(() => {
console.log('created user');
})
.catch((err) => {
console.log('Error adding user: ' + err);
});
}
updateUserData(user) {
const userRef: AngularFirestoreDocument<any> = this.db.doc(
`users/${user.uid}`,
);
const userPermissions = this.addPermissions(userRef);
console.log(userPermissions); // This works
const data: User = {
uid: user.uid,
email: user.email,
photoURL: user.photoURL,
displayName: user.displayName,
roles: {
member: true,
}, // I need to make sure this keeps current user roles
permissions: userPermissions,
};
console.log(data); // This works
userRef
.set(data)
.then(() => {
console.log('Success: Data for userDoc overwritten');
})
.catch((err) => {
console.error('Error writing to userDoc: ' + err);
});
}
addPermissions(userRef) {
const tempPermissions = [];
userRef.valueChanges().subscribe((userdata) => {
if (userdata.roles.reader === true) {
tempPermissions.push(this.permissionsService.memberPermissions);
}
if (userdata.roles.author === true) {
tempPermissions.push(this.permissionsService.authorPermissions);
}
if (userdata.roles.admin === true) {
tempPermissions.push(this.permissionsService.adminPermissions);
}
});
return tempPermissions;
}
checkPermissions(permission: string) {
if (!this.user) {
return false;
} else {
this.user.subscribe((data) => {
for (const p of data.permissions) {
if (p === permission) {
return true;
}
}
return false;
});
}
}
logout() {
this.afAuth.auth.signOut();
this.user = null;
}
}
I checked the documentation on the .doc() function and it should work fine with 0 arguments. It should be returning an empty doc reference. However, it keeps throwing the error saying it expects 1 argument. Any idea why this isn't working?
Please help me. I've made Database Provider to connect with SQLite in ionic 3. When i want to get the data rows it's always getting null but when I check data length it has 1
This is my DatabaseProvider
import { Injectable } from '#angular/core';
import { Platform } from 'ionic-angular';
import { SQLite, SQLiteObject } from '#ionic-native/sqlite';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Storage } from '#ionic/storage';
#Injectable()
export class DatabaseProvider {
private db: SQLiteObject;
private databaseReady: BehaviorSubject<boolean>;
constructor(private storage: Storage, private sqlite: SQLite, private platform: Platform) {
this.databaseReady = new BehaviorSubject(false);
this.platform.ready().then(() => {
this.sqlite.create({
name: 'takia.db',
location: 'default'
}).then((database: SQLiteObject) => {
this.db = database;
this.storage.get('database_filled').then(val => {
if (val) {
this.databaseReady.next(true);
} else {
this.initDB();
}
});
}).catch(e => { console.log(e); });
});
}
initDB(){
this.db.executeSql('CREATE TABLE IF NOT EXISTS users(user_id INTEGER PRIMARY KEY, username TEXT, email TEXT, password TEXT)', {})
.then(res => {
this.db.executeSql('INSERT INTO users VALUES(NULL,?,?,?,?)',['admin','admin.#email.com','password'])
.then(res => {
this.databaseReady.next(true);
this.storage.set('database_filled', true);
}).catch(e => {
console.log(e);
});
}).catch(e => {
console.log(e)
});
this.db.executeSql('CREATE TABLE IF NOT EXISTS questions(user_id INTEGER PRIMARY KEY, username TEXT, email TEXT, password TEXT)', {})
.then(res => {
this.db.executeSql('INSERT INTO users VALUES(NULL,?,?,?,?)',['admin','admin.tazkiaiibs.sch.id','bismillah'])
.then(res => {
this.databaseReady.next(true);
this.storage.set('database_filled', true);
}).catch(e => {
console.log(e);
});
}).catch(e => {
console.log(e)
});
}
getUser(){
return this.db.executeSql('SELECT user_id, username, email, password, COUNT(*) total FROM users', [])
.then(res => {
let users = [];
if (res.rows.length > 0) {
for (var i = 0; i < res.rows.length; i++) {
let row = res.rows.item(i);
users.push(row);
}
}
return users;
}, err => {
console.log('Error: ', err);
return [];
});
}
getDatabaseState() {
return this.databaseReady.asObservable();
}
}
and this is my code in component
constructor(public navCtrl: NavController,
public navParams: NavParams,
private dbProvider: DatabaseProvider,
private toastCtrl: ToastController) {
this.loadData();
}
loadData(){
this.dbProvider.getUser().then(data=>{
if(data.length>0){
this.id = data[0].id;
this.old_password = data[0].password;
this.username = data[0].username;
this.email = data[0].email;
let toast = this.toastCtrl.create({
message: 'ID '+data[0].username,
duration: 3000
});
toast.present();
}else{
let toast = this.toastCtrl.create({
message: 'No data'+data.length,
duration: 3000
});
toast.present();
}
});
}
When i run loadData function the length is not 0 but the data is null.
The comment under the question seemed to help, so I form it as an answer to hopefully collect some reputation points.
The problem seems to be a misformed SQL-query. The count(*) part makes the query return at least one row. Therefore the other fields might be NULL, when queried before data is added to the database.
The function "getUser" is called before the promise callback is executed.
I would like to know how to use Sqlite with Ionic 2 rc.o release.I am finding it difficult as there are no examples for the latest version release and i am stuck.Nothing on the net seems to be updated.A supporting example for Sqlite would be of great use.
Thank you in advance.
1) First of all, navigate to the root folder of your project and add the plugin:
$ ionic plugin add cordova-sqlite-storage
$ npm install --save #ionic-native/sqlite
2) Create a new provider inside the project (in this example, called SqlStorage):
$ ionic g provider sqlStorage
3) I'd like to add an import to app.component.ts to initialize the plugin at startup, not mandatory:
import {SqlStorage} from '../providers/sql-storage';
...
...
constructor(public sqlStorage: SqlStorage){}
4) Add entry to app.module.ts, mandatory:
import { SQLite } from '#ionic-native/sqlite';
import { SqlStorage } from '../providers/sql-storage';
...
...
providers: [SQLite, SqlStorage]
5) Define the sql-storage.ts provider:
import { Injectable } from '#angular/core';
import { Platform } from 'ionic-angular';
import { SQLite, SQLiteObject } from '#ionic-native/sqlite';
#Injectable()
export class SqlStorage {
storage: any;
DB_NAME: string = '__ionicstorage';
constructor(public platform: Platform, public sqlite: SQLite) {
this.platform.ready().then(() => {
this.sqlite.create({ name: this.DB_NAME, location: 'default' })
.then((db: SQLiteObject) => {
this.storage = db;
this.tryInit();
});
});
}
tryInit() {
this.query('CREATE TABLE IF NOT EXISTS kv (key text primary key, value text)')
.catch(err => {
console.error('Unable to create initial storage tables', err.tx, err.err);
});
}
/**
* Perform an arbitrary SQL operation on the database. Use this method
* to have full control over the underlying database through SQL operations
* like SELECT, INSERT, and UPDATE.
*
* #param {string} query the query to run
* #param {array} params the additional params to use for query placeholders
* #return {Promise} that resolves or rejects with an object of the form
* { tx: Transaction, res: Result (or err)}
*/
query(query: string, params: any[] = []): Promise<any> {
return new Promise((resolve, reject) => {
try {
this.storage.transaction((tx: any) => {
tx.executeSql(query, params,
(tx: any, res: any) => resolve({ tx: tx, res: res }),
(tx: any, err: any) => reject({ tx: tx, err: err }));
},
(err: any) => reject({ err: err }));
} catch (err) {
reject({ err: err });
}
});
}
/** GET the value in the database identified by the given key. */
get(key: string): Promise<any> {
return this.query('select key, value from kv where key = ? limit 1', [key])
.then(data => {
if (data.res.rows.length > 0) {
return data.res.rows.item(0).value;
}
});
}
/** SET the value in the database for the given key. */
set(key: string, value: string): Promise<any> {
return this.query('insert into kv(key, value) values (?, ?)', [key, value]);
}
/** REMOVE the value in the database for the given key. */
remove(key: string): Promise<any> {
return this.query('delete from kv where key = ?', [key]);
}
}
6) In your .ts page:
import {SqlStorage} from '../../providers/sql-storage';
export class ExamplePage {
constructor(public sqlStorage: SqlStorage) {
// this.sqlStorage.query(...);
// this.sqlStorage.get(key).then(data => {
// console.log(data);
// }
//...
}
}
Credit to: https://github.com/NickStemerdink with some personal changes.
Hope it will help and works fine :)
EDIT: Still works fine with Ionic v3.0.1 (2017-04-06)
in app.module.ts
import { SQLite } from '#ionic-native/sqlite';
providers: [
StatusBar,
SplashScreen,
SQLite,
{ provide: ErrorHandler, useClass: IonicErrorHandler }
]
in database provider
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
//import { Storage } from '#ionic/storage';
import { SQLite, SQLiteObject } from '#ionic-native/sqlite';
import { Platform } from 'ionic-angular';
/*
Generated class for the Database provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
#Injectable()
export class Database {
DB_NAME: string = 'ssddb';
constructor(public http: Http, public platform: Platform, public sqlite: SQLite) {
this.platform.ready().then(() => {
this.configureDatabase();
});
}
configureDatabase() {
this.query('CREATE TABLE IF NOT EXISTS EMP (key text primary key, value text)')
.catch(err => {
console.error('Unable to create initial storage tables', err.tx, err.err);
});
}
query(query: string, params: any[] = []): Promise<any> {
return new Promise((resolve, reject) => {
try {
this.sqlite.create({
name: this.DB_NAME,
location: 'default'
})
.then((db: SQLiteObject) => {
db.transaction((tx: any) => {
tx.executeSql(query, params,
(tx: any, res: any) => resolve({ tx: tx, res: res }),
(tx: any, err: any) => reject({ tx: tx, err: err }));
})
})
.catch(e => console.log(e));
} catch (err) {
reject({ err: err });
}
});
}
get(key: string): Promise<any> {
return this.query('select key, value from EMP where key = ? limit 1', [key])
.then(data => {
if (data.res.rows.length > 0) {
return data.res.rows.item(0).value;
}
});
}
set(key: string, value: string): Promise<any> {
return this.query('insert into EMP(key, value) values (?, ?)', [key, value]);
}
}
in page.ts
this.database.set("333","ss");
this.database.get("333").then(data => {
console.log(data);
let toast = this.toastCtrl.create({
message: data,
duration: 10000,
position: 'bottom'
});
toast.present();
});
On ionic-storage repo they say to use Ionic Native SQLite plugin.
So like this:
import { SQLite } from 'ionic-native';
SQLite.openDatabase({
name: 'data.db',
location: 'default'
})
.then((db: SQLite) => {
db.executeSql('create table danceMoves(name VARCHAR(32))', {}).then(() => {}).catch(() => {});
})
.catch(error => console.error('Error opening database', error));