Is IonicStorage only meant to be injected on @Components?

#1

Hi there! Thanks for reading this.

I’m trying to inject the Storage provider from IonicStorage native into a provider that I created but I get an error:

**Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[LocStorageProvider -> Storage]: **
** StaticInjectorError(Platform: core)[LocStorageProvider -> Storage]: **
** NullInjectorError: No provider for Storage!**

If I inject the Storage provider from native, directly into de @Component, there is no error, but I need it to be behind a provider, so I could add some logic to the persistence interaction.

For testing purpouses, Im injecting the Storage and my LocStorageProvider inside home.ts so you could see it together, but hopefully, the home.ts will only know the LocStorageProvider.

Please, tell me if I could add any more information to better toubleshoot the problem

I have “@ionic/storage”: “2.2.0” on my package json and Im using ionic 4.5.0

Thanks for your time!

app.module.ts

imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    IonicStorageModule.forRoot()
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    TabsPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    LocStorageProvider
  ]```

**home.ts**

constructor(public navCtrl: NavController,public storage: Storage, private storageProvider: LocStorageProvider) {
storage.ready().then(() => {
this.storage.set(‘test’, {id: 1});
this.storage.get(‘test’).then(value => {
console.error(value)
});});

storageProvider.storage.ready().then(() => {
  this.storage.set('test', {id: 1});
  this.storage.get('test').then(value => {
    console.error(value)
  });});

}
}


**loc-storage.ts**

import { Injectable } from ‘@angular/core’;

@Injectable()
export class LocStorageProvider {

constructor(public storage: Storage) {
this.storage.set(‘test’, {id: 1});
this.storage.get(‘test’).then(value => {
console.error(value)
});
}

}

#2

I have a feeling this might be the topic of chapter 952 of Horrible Things About JavaScript: namespaces.

Since you have posted one import line from loc-storage.ts, I’m going to assume that it’s the only one, and if so, that’s your problem. Storage is also defined in lib.dom.d.ts, which since it’s unrelated to Ionic’s Storage, DI doesn’t understand that you want to inject the Ionic one. The solution would be to import Storage from @ionic/storage in loc-storage.ts.

1 Like
#3

That was it! Thanks raproppos!

For some reason, on home.ts, the component, the right Storage from ‘@ionic/storage’ was auto imported, and in the locStorageProvider was not jaja.

You are the man!!

Thank you! again

Abrazo!