Wednesday, January 4, 2017

Ionic 2 @ionic/storage not working on Android device

Leave a Comment

I am using localstorage with ionic2 which works locally in chrome and on iphone but doesn't seem to work on Android device.

I don't really want to re-write and use Sqlite as my data fits json structure better than table structure. Any clues?

CODE

import { Injectable } from '@angular/core'; import { Storage } from '@ionic/storage'; import { Observable } from 'rxjs/Rx';  import { Customer } from '../pages/customer/customer.model'  @Injectable() export class StorageService {     constructor(private _storage: Storage) { }      setSelectedCustomer(customer: Customer) {         return Observable.fromPromise(this._storage.set('selectedCustomer', customer));     } } 

versions:

"@ionic/storage": "^1.1.7", "ionic-angular": "2.0.0-rc.3", "ionic-native": "2.2.3", 

Thanks

2 Answers

Answers 1

It is not a good idea to use localStorage to save important data in hybrid apps. There were too many reports about problems on android and sometime on iOS. Generally it was caused by improper data type handling. As example you're trying to save some object, but in chrome and android is could be serialized differently. So it is better to do it manually like:

this._storage.set('selectedCustomer', JSON.stringify(customer)) 

And then parse your object from json string using JSON.parse The problem that mentioned in this article is still remains. So it is better to use something more robust to store user data(like SQLite)

Also, if you don't want to change the structure from json to relational tables you could try LokiJS

Answers 2

i use it like this and its work fine

this._storage.set('selectedCustomer', JSON.stringify(customer));  this._storage.get('selectedCustomer').then((selectedCustomer) => {     let json_selectedCustomer = JSON.parse(selectedCustomer);     }); 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment