Thomas Degroot Thomas Degroot - 2 months ago 20
AngularJS Question

How to save data from external server (JSON) into ionic 2 mobile app with sqlite database

All my searching has found posts on ionic 1. on the following code I am able use this.corpguys in ng*For and save to local storage. I want to take my Apps further and save this to a sqlite table corpguys. I am not sure if I have to JSON.stringify(data) and then loop through to insert this data into to db. i am just wondering if anyone has seen examples of 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.corpguys = null;
this.http.get('http://test.json')
.map(res => res.json())
.subscribe
(data => {
this.corpguys = data;

//Loop through corpguys and asign varible names

this.DataStorage = new Storage(SqlStorage);
this.DataStorage.query("INSERT into corpguys (name, position, phone, cell, sms, email, other) VALUES ('namevalue', 'positionvalue', 'phonevalue', 'cellvalue', 'smsvalue', 'emailvalue', 'othervalue')");
},
err => {
console.log("screwed up again!")
}
});
}

Answer

I decided to save as a key value pair instead. Here is my final code

import { Component } from '@angular/core';
import { Storage } from '@ionic/storage';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/timeout';
import { NavController, AlertController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})

export class HomePage {
    mainContact: any;

    constructor(public navCtrl: NavController, public http: Http, public storage: Storage, public alertCtrl: AlertController) {
        this.mainContact = null;
        this.http.get('http://www.somejson.php')
            .timeout(4000)
            .map(res => res.json())
            .subscribe(data => {
                this.mainContact = data;
                //console.log(data);
                this.storage.set ("mainContact", JSON.stringify(data));
                },
                err => {
                    //console.log("http fail!");
                    this.connectionAlert();
                    this.storage.get("mainContact").then((value) => {
                    this.mainContact = JSON.parse(value));
                }
            );
    }//end constructor

    connectionAlert() {
        let alert = this.alertCtrl.create({
            title: 'Connection Error',
            subTitle: 'Your network coverage is too weak for updates.  Previously downloaded data will be used.',
            buttons: ['CONTINUE']
        });
        alert.present();
    }
}
Comments