IONIC 3新的本地存储

时间:2017-12-07 20:15:35

标签: ionic3 ionic-storage

我想在我的离子应用程序(IONIC 3)中创建一个新的本地存储,但我看了很多方法。我目前有这个:

database.ts(我的提供者)

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);
  }



}

但IDE告诉我,“ this.localData = new Storage(localStorage); ”行中的错误可能需要特殊导入。我安装了“@ ionic / storage”:“2.1.3”。

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

除非要指定类似于perferred db的设置,否则不需要为存储构造函数提供参数。 以下是在提供程序中使用存储的示例 -

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);
  }    
}

答案 1 :(得分:0)

我正在使用sql storage 2.2,到目前为止我还没有遇到任何问题

将其安装为

ionic cordova plugin add cordova-sqlite-storage

然后

npm install --save @ionic/storage

至于文档Ionic Storage,您需要将存储服务添加到模块

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

然后你可以像这样使用它

        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)));
         }
     }

请记住,我刚刚根据工作解决方案编写了这个,但未经过测试

相关问题