web-dev-qa-db-fra.com

Erreur Ionic2: "Aucun fournisseur pour le stockage"

Après avoir lu tout ce que j'ai pu trouver et échoué, je dois demander ici:

J'essaie d'utiliser le stockage ionic2, comme le dit la doc,

doc: https://ionicframework.com/docs/storage/

voici mon code:

app-module.ts

    import { BrowserModule } from '@angular/platform-browser';
    import { ErrorHandler, NgModule } from '@angular/core';
    import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
    import { SplashScreen } from '@ionic-native/splash-screen';
    import { StatusBar } from '@ionic-native/status-bar';

    import { MyApp } from './app.component';
    import { HomePage } from '../pages/home/home';
    import { Intro } from '../pages/intro/intro';
    import { Checklist } from '../pages/checklist/checklist';
    // import { Http } from '@angular/http';
    import {IonicStorageModule} from '@ionic/Storage';
    import { Data } from '../providers/data';
    import {HttpModule} from '@angular/http';
    // import {Storage} from '@ionic/storage';


    @NgModule({
      declarations: [
        MyApp,
        HomePage,
        Intro,
        Checklist
      ],
      imports: [
        HttpModule,
        BrowserModule,
        IonicModule.forRoot(MyApp),
        IonicStorageModule.forRoot()
      ],
      bootstrap: [IonicApp],
      entryComponents: [
        MyApp,
        HomePage,
        Intro,
        Checklist
      ],
      providers: [
        StatusBar,
        SplashScreen,
        {provide: ErrorHandler, useClass: IonicErrorHandler},
        // Storage,
        //Http,
        Data
      ],
    })
    export class AppModule {}


data.ts

import { Injectable } from '@angular/core';
// import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
// import { HttpModule } from '@angular/http';

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


@Injectable()
export class Data {
  constructor(public storage: Storage) {
  }
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  getData(): Promise<any> {
    return this.storage.get('checklists');
  }
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  save(data): void {
    let saveData = [];
    //Remove observables
    data.forEach((checklist) => {
      saveData.Push({
        title: checklist.title,
        items: checklist.items
      });
    });
    let newData = JSON.stringify(saveData);
    this.storage.set('checklists', newData);
  }
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}

home.ts

// import { Component } from '@angular/core';
// import { NavController } from 'ionic-angular';

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

//   constructor(public navCtrl: NavController) {

//   }

// }


import { Component } from '@angular/core';
import { NavController, AlertController, Platform } from 'ionic-angular';
import { Checklist } from '../checklist/checklist';
import { ChecklistModel } from '../../models/checklist-model';
import { Data } from '../../providers/data';
import { Keyboard } from 'ionic-native';
@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
})
export class HomePage {
  checklists: ChecklistModel[] = [];

  constructor(public navCtrl: NavController, public dataService: Data,
    public alertCtrl: AlertController, public platform: Platform) {
  }

  // constructor(public navCtrl: NavController, public alertCtrl: AlertController, public platform: Platform) {
  //   // this.checklists.Push(new ChecklistModel("Noam", [1,2,3]));
  // }
  ///////////////////////////////////////////////////////////////////////////////////////////////////////////
  ionViewDidLoad() {
  }
  ///////////////////////////////////////////////////////////////////////////////////////////////////////////
  addChecklist(): void {
    let Prompt = this.alertCtrl.create({
      title: 'New Checklist',
      message: 'Enter the name of your new checklist below:',
      inputs: [
        {
          name: 'name'
        }
      ],
      buttons: [
        {
          text: 'Cancel'
        },
        {
          text: 'Save',
          handler: data => {
            let newChecklist = new ChecklistModel(data.name, []);
            this.checklists.Push(newChecklist);
            newChecklist.checklistUpdates().subscribe(update => {
              this.save();
            });
            this.save();
          }
        }
      ]
    });
    Prompt.present();
  }
  ///////////////////////////////////////////////////////////////////////////////////////////////////////////
  renameChecklist(checklist): void {
    let Prompt = this.alertCtrl.create({
      title: 'Rename Checklist',

      message: 'Enter the new name of this checklist below:',
      inputs: [
        {
          name: 'name'
        }
      ],
      buttons: [
        {
          text: 'Cancel'
        },
        {
          text: 'Save',
          handler: data => {
            let index = this.checklists.indexOf(checklist);
            if (index > -1) {
              this.checklists[index].setTitle(data.name);
              this.save();
            }
          }
        }
      ]
    });
    Prompt.present();
  }
  ///////////////////////////////////////////////////////////////////////////////////////////////////////////
  viewChecklist(checklist): void {
    this.navCtrl.Push(Checklist, {
      checklist: checklist
    });
  }
  ///////////////////////////////////////////////////////////////////////////////////////////////////////////
  removeChecklist(checklist): void {
    let index = this.checklists.indexOf(checklist);
    if (index > -1) {
      this.checklists.splice(index, 1);
      this.save();
    }
  }
  ///////////////////////////////////////////////////////////////////////////////////////////////////////////
  save(): void {
    Keyboard.close();
    this.dataService.save(this.checklists);
  }
  ///////////////////////////////////////////////////////////////////////////////////////////////////////////
}

La méthode censée être appelée et utiliser le stockage est la save() de HomePage.

Je ne peux pas aller aussi loin, cependant, car avant même que la page soit chargée, je reçois

Erreur d'exécution non capturée (promis): Erreur: Aucun fournisseur pour le stockage! Erreur à g ( http: // localhost: 8100/build/polyfills.js: 3: 71 ) à injectionError ( http: // localhost: 8100/build/main.js: 1585: 86 ) à noProviderError ( http: // localhost: 8100/build/main.js: 1623: 12 ) à ReflectiveInjector _. throwOrNull (- http: // localhost: 8100/build/main.js: 3125: 19 ) sur ReflectiveInjector . getByKeyDefault ( http: // localhost: 8100/build/main.js: 3164: 25 ) sur ReflectiveInjector . getByKey ( http : // localhost: 8100/build/main.js: 3096: 25 ) à ReflectiveInjector . get ( http: // localhost: 8100/build/main. js: 2965: 21 ) sur AppModuleInjector.get (ng: ///AppModule/module.ngfactory.js: 254: 82) sur AppModuleInjector.getInternal (ng: ///AppModule/module.ngfactory.js: 481 : 44) à AppModuleInjector.NgModuleInjector.get ( http: // localhost: 8100/build/main.js: 3929: 44 ) à resolDep ( http: // localhost: 8100/build/main.js: 11334: 45 ) à createClass ( http: // localhost: 8100/build/main.js: 11202: 32 ) à createDire ctiveInstance ( http: // localhost: 8100/build/main.js: 11028: 37 ) sur createViewNodes ( http: // localhost: 8100/build/main.js: 12377: 49 ) à createRootView ( http: // localhost: 8100/build/main.js: 12282: 5 )

Package.json:

{
  "name": "ionic-hello-world",
  "author": "Ionic Framework",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "config": {
    "ionic_source_map": "source-map"
  },
  "scripts": {
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build",
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/common": "4.0.0",
    "@angular/compiler": "4.0.0",
    "@angular/compiler-cli": "4.0.0",
    "@angular/core": "4.0.0",
    "@angular/forms": "4.0.0",
    "@angular/http": "4.0.0",
    "@angular/platform-browser": "4.0.0",
    "@angular/platform-browser-dynamic": "4.0.0",
    "@ionic-native/core": "3.4.2",
    "@ionic-native/splash-screen": "3.4.2",
    "@ionic-native/status-bar": "3.4.2",
    "@ionic/storage": "^2.0.1",
    "ionic-angular": "3.0.1",
    "ionic-native": "^2.9.0",
    "ionicons": "3.0.0",
    "rxjs": "5.1.1",
    "sw-toolbox": "3.4.0",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@ionic/app-scripts": "1.3.0",
    "TypeScript": "~2.2.1",
    "webpack": "^2.4.1"
  },
  "cordovaPlugins": [
    "cordova-plugin-whitelist",
    "cordova-plugin-console",
    "cordova-plugin-statusbar",
    "cordova-plugin-device",
    "cordova-plugin-splashscreen",
    "ionic-plugin-keyboard"
  ],
  "cordovaPlatforms": [],
  "description": "quicklists: An Ionic project"
}

Puisque j'ai fait tout ce que le doc a dit, s'il vous plait, éclairez moi - Ce qui manque pour que le Stockage ne soit pas trouvé

Merci

20
Gulzar

Tout d'abord, vous devez installer: npm install --save @ionic/storage

Le problème était dans app.ts:

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

Capital 'S' au lieu de non capital 's':

from '@ionic/Storage'

au lieu de:

from '@ionic/storage'

Aucune idée pourquoi le compilateur ne comprendrait pas cela si c'était un problème, mais ça ne l'a pas été.

Merci à @chairmanmow

27
Gulzar

Dans mon cas, j'ai oublié d'ajouter ce qui suit dans app.module.ts

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

@NgModul({ 
  ..., 
  Imports: [
  ...
    IonicStorageModule.forRoot()
],
15
VictorL

commencez par installer npm --save @ ionic/storage

J'ai réussi à obtenir ce travail en utilisant ceci ..

À l'intérieur app.module.ts

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

Et alors ...

providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}, Storage]

Et puis dans mon page.ts

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

Dans le constructeur ...

public storage: Storage

Et puis dans les entrailles de mon code ..

this.storage.get('date').then((value) => {
  // blah
});
7
Chris
Please use this plugin for native storage         

 ionic cordova plugin add cordova-plugin-nativestorage
 npm install --save @ionic-native/native-storage

et importer app.module.ts

import { NativeStorage } from '@ionic-native/native-storage';

  providers: [
    StatusBar,
    SplashScreen,
     NativeStorage,
      LocalStorageProvider,
    {provide: ErrorHandler, useClass: IonicErrorHandler}

  ]

entrez le code ici

2
Mahadev Dalavi