IONIC 3 new local storage

7.9k Views Asked by At

I want to create a new localstorage in my ionic app (IONIC 3), but I've looked many ways to do that. I currently have this:

database.ts (my provider)

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

import { Storage } from '@ionic/storage';

@Injectable()
export class DatabaseProvider {


  localData: Storage;

  constructor(public http: HttpClient) {


    this.localData = new Storage(localStorage);
  }



}

but the IDE told me that it's a mistake in the line "this.localData = new Storage(localStorage);" maybe it requires a special import. I have installed the "@ionic/storage": "2.1.3".

Thanks for your help!

2

There are 2 best solutions below

2
Philip Brack On

You do not need to provide an argument to storage constructor unless you want to specify settings like the perferred db. Here is an example of using Storage in a provider-

LocalNotes.ts

import {Injectable} from '@angular/core';
import {Storage} from '@ionic/storage';


@Injectable()
export class LocalNotes {
  local:any;

  constructor() {
    this.local = new Storage();
  }

  getNotes() {
    return new Promise((resolve, reject)=> {
      this.local.get('userNotes')
        .then((answer)=> {
          resolve(answer);
        })
        .catch((err) => {
          reject(err);
          });
      });
  }

  setNotes(notes:string[]) {
    this.local.set('userNotes', notes);
  }    
}
0
hiram acebo On

I am using sql storage 2.2 and so far I havent had any problem

Install it as

ionic cordova plugin add cordova-sqlite-storage

then

npm install --save @ionic/storage

As for the documentation Ionic Storage you need to add the storage service to your module

import { IonicStorageModule } from '@ionic/storage';
@NgModule({
  declarations: [
    // ...
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    IonicStorageModule.forRoot()<---------- THIS
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    // ...
  ],
  providers: [
    // ...
  ]
})
export class AppModule {}

then you could use it like this

        import { HttpClient } from '@angular/common/http';
        import { Injectable } from '@angular/core';
        import {Observable} from "rxjs/Observable";
        import 'rxjs/add/observable/fromPromise';
        import { Storage } from '@ionic/storage';

        @Injectable()
        export class DatabaseProvider {
          constructor(public http: HttpClient, private _storage:Storage) {
          }
          getData(keyName:string):Observable<any> {
           return  Observable.fromPromise(this._storage.get('keyName'));
         }
          setData(keyName:string,data:any):Observable<any>{
           return  Observable.fromPromise(this._storage.set(keyName,JSON.stringify(data)));
         }
     }

Please have in mind I just wrote this based on working solution but this is not tested