Accessing sqlite Key Value pair in ng*For

With the following code I am able HTTP get a remote JSON use it in a ng*For and save it as a key value pair in sqlite successfully.

What I am trying accomplish is when I have a connection error i.e no cellular connection, is fall back on storage.get to JSON.parse the data in the sqlite db and use it for the ng*For. I have done this with Ionic 1 but a little unsure how I would accomplish this with ionic 2

import {Page, Storage, SqlStorage} from ‘ionic/ionic’;
import {Http} from ‘angular2/http’;
import ‘rxjs/add/operator/map’;
@Page ({
templateUrl: ‘build/pages/remote/remote.html’,
})
export class Remote {
constructor(http: Http) {
this.http = http;
this.corptest = null;
this.storage = new Storage(SqlStorage);
this.http.get(‘http://www.something/test.json’)
//.timeout(1000)
.map(res => res.json())
.subscribe

	    (data => {
	        this.corptest = data;
			this.storage.set ("corptest", JSON.stringify(data));
		},

		err => {

                   //Error is here
		this.storage.get ("corptest", JSON.parse(data));                
			console.log("screwed up still!")
		}
});

}

1 Like

Well whats the issue? i see you need to open the database like this.storage = new Storage(SqlStorage, {name: 'databasename'}).

Also get uses 2 values, the key and value, the get uses 1, just the key, the return value of get is a promise so use .then() to deal with the data.

Thanks for the help,

I did not need open the db as you said as I set it up with with a few tables in app.js file.

I changed my error code to this

err => {
  console.log("http fail!")
  this.storage.get("corptest").then((value) => {
  this.corptest = ("value", JSON.parse(value));
  })
}

and everything worked like a charm.

It’s not like you need a name, probably the sqLite plugin uses a name by default, it’s just a good idea to give it a name you can easily recognize so when you need to debug it you know what file to erase, or what webSql db to clear when you need to clear the db just for the ionic app.

I will try that. Thanks again