簡體   English   中英

Ionic2 錯誤:“沒有存儲提供程序”

[英]Ionic2 Error: "No provider for Storage"

在閱讀了我能找到的所有內容並失敗后,我必須在這里問:

我正在嘗試使用 ionic2 的存儲,就像文檔告訴我的那樣,

文檔: https://ionicframework.com/docs/storage/

這是我的代碼:

應用模塊.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);
  }
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}

主頁.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);
  }
  ///////////////////////////////////////////////////////////////////////////////////////////////////////////
}

應該調用和使用存儲的方法是 HomePage 的save()

但是,我不能走那么遠,因為在頁面加載之前,我得到了

運行時錯誤未捕獲(承諾):錯誤:在 injectionError ( http ://localhost:8100/build/main .js:1585:86 ) 在 ReflectiveInjector_ 的 noProviderError ( http://localhost:8100/build/main.js:1623:12 )。 在 ReflectiveInjector 的 throwOrNull ( http://localhost:8100/build/main.js:3125:19 ) 在 ReflectiveInjector 的 getByKeyDefault ( http://localhost:8100/build/main.js:3164:25 ) GetByKey ( http://localhost:8100/build/main.js:3096:25 ) 在 ReflectiveInjector .get ( http://localhost:8100/build/main.js:2965:21 ng) 在 App.ModuleInject: ///AppModule/module.ngfactory.js:254:82) 在 AppModuleInjector.getInternal (ng:///AppModule/module.ngfactory.js:481:44) 在 AppModuleInjector.NgModuleInjector.get ( http://localhost: 8100/build/main.js:3929:44 ) 在 resolveDep ( http://localhost:8100/build/main.js:11334:45 ) 在 createClass ( http://localhost:8100/build/ 11202:32 ) at createDirectiveInstance ( http://localhost:8100/build/main.js:11028:37 ) at createViewNodes ( http://localhost:8100/build/main.js:12377:49 ) at 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"
}

由於我做了文檔所說的一切,請賜教-仍然缺少什么會導致找不到存儲

謝謝

首先你需要安裝: npm install --save @ionic/storage

問題出在 app.ts 中:

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

大寫“S”而不是非大寫“s”:

from '@ionic/Storage'

代替:

from '@ionic/storage'

不知道為什么編譯器不會在有問題的情況下捕獲它,但它沒有。

感謝@chairmanmow

就我而言,我忘記在 app.module.ts 中添加以下內容

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

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

首先做這個 npm install --save @ionic/storage

我設法使用這個來讓它工作..

app.module.ts里面

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

進而 ...

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

然后在我的page.ts

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

在構造函數中...

public storage: Storage

然后在我的代碼中..

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

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

並導入app.module.ts

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

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

  ]

在此處輸入代碼

我遇到過同樣的問題。 我將此添加到app.module.ts

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

並且,這將導入app.module.ts部分app.module.ts

IonicStorageModule.forRoot(),

2021 離子存儲 v3 Angular:

import { IonicStorageModule } from '@ionic/storage-angular';
IonicStorageModule.forRoot(),

我有同樣的問題。 請確保您記得在app.module.ts文件中添加主模塊

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

@NgModule({ 
  ..., 
  Imports: [
    ...
    IonicStorageModule.forRoot()
  ],
  ....
})

還要確保您實際上是從@ionic/storage-angular導入實際的Storage

constructor(private storage: Storage) { }

上面的內容看起來不錯,即使您不包含也不會顯示任何錯誤

import { Storage } from '@ionic/storage-angular'

在文件的頂部。 我認為這是因為全局window對象上可用的本機Storage

文檔中解釋的注入( https://github.com/ionic-team/ionic-storage )效果很好;

我首先錯過了這個信息:“這種方法適用於單個組件”,因此,將它用於 AppComponent 和 HomePage 我確實得到了這個錯誤。

我在之前的 state 中恢復了 app.component.ts,現在一切正常。 (適用於離子 6.20.1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM