Error in Injecting Storage in Ionic 4: Provider Not Found

Currently, I am working with Ionic 4 and using node 8.x. My goal is to inject Storage into my app in order to retrieve a token from my authentication service. However, I am encountering the following error:

StaticInjectorError(AppModule)[Storage]: 
  StaticInjectorError(Platform: core)[Storage]: 
    NullInjectorError: No provider for Storage!
    at 

I have looked into similar issues faced by others, but it seems like their problems were related to type errors which I don't believe is the case for me.

Below is an excerpt from my app.module:


import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

import { HttpClientModule } from '@angular/common/http';
import { Storage, IonicStorageModule } from '@ionic/storage';
import { JwtModule, JWT_OPTIONS } from '@auth0/angular-jwt';

export function jwtOptionFactory(storage) {
  return {
    tokenGetter: () => {
      return storage.get('access_token')
    },
    whitelistedDomains: ['localhost:5000']
  }
}

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule, 
    IonicModule.forRoot(),
    AppRoutingModule,
    HttpClientModule, 
    IonicStorageModule.forRoot(),
    JwtModule.forRoot({
      jwtOptionsProvider: {
        provide: JWT_OPTIONS,
        useFactory: jwtOptionFactory,
        deps: [Storage]
      }
    })
  ],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

I suspect that the error is related to deps: [Storage], however, I cannot seem to find a solution for this issue.

Answer №1

After encountering a similar issue, I was able to resolve it by including the following code snippets into my app.module.ts file:

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

Make sure to also include the same code snippet in the imports section:

imports: [
    BrowserModule,
    HttpClientModule,
    IonicModule.forRoot(),
    IonicStorageModule.forRoot(),
    AppRoutingModule
  ]

Answer №2

If you're finding your way here via a Google search and are using PhpStorm, I encountered an issue where the import statement for storage was not automatically added to the page due to the app.module import. As a result, my code transformed from its original form:

export class MyApp {
  constructor(private storage: Storage) { }

  ...

  // set a key/value
  storage.set('name', 'Max');

  // Or to retrieve a key/value pair
  storage.get('age').then((val) => {
    console.log('Your age is', val);
  });
}

To this adjusted version:

import { Storage } from '@ionic/storage'; // Manually added this line.

export class MyApp {
  constructor(private storage: Storage) { }

  ...

  // set a key/value
  storage.set('name', 'Max');

  // Or to retrieve a key/value pair
  storage.get('age').then((val) => {
    console.log('Your age is', val);
  });
}

Answer №3

I encountered a similar issue with the error message "No provider for Storage".

However, I was able to resolve the problem by manually adding Storage, to my import statement, as my IDE only generated

import { IonicStorageModule } from "@ionic/storage";
. This solution may not apply to your specific situation, but hopefully it can assist other readers in the future.

Answer №4

An error occurred in my component's .ts file due to exporting the wrong storage dependency injection. Initially, I mistakenly used 'storage' instead of 'store', causing a debugging headache. Once I corrected the import, the error was resolved.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Typescript validation for redundant property checks

Why am I encountering an error under the 'name' interface with an excess property when using an object literal? There is no error in the case of a class, why is this happening? export interface Analyzer { run(matches: MatchData[]): string; } ...

From integrating Vue 2 TSX to React TSX: ensuring seamless cooperation

Currently, my app is built with Vue 2 using vue-tsx-support, vue-class-component, and vue-property-decorator. All of my Vue 2 components are already TSX classes. I am interested in gradually transitioning to React. I experimented with https://github.com/ ...

Why is it that I am not receiving JSON data in my Angular application?

I am currently working on a class within a webapi public class ResponseObject { public int Success { get; set; } public string Message { get; set; } public object Data { get; set; } } Within my ASP.NetCore, I have the following method: publi ...

typegrapql encounters an issue with experimentalDecorators

I'm currently delving into TypeGraphQL and working on building a basic resolver. My code snippet is as follows: @Resolver() class HelloReslover { @Query(() => String) async hello(){ return "hello wtold" } } However, ...

Toggle the presence of a string in an array with a checkbox

Currently, I am working on a user creation form for my Next.js front end project using TypeScript. The main goal is to allow an administrator to create new users by filling out a simple form which will generate a basic user object. Here is the structure of ...

Solving runtime JavaScript attribute issues by deciphering TypeScript compiler notifications

Here is a code snippet I am currently working with: <div class="authentication-validation-message-container"> <ng-container *ngIf="email.invalid && (email.dirty || email.touched)"> <div class="validation-error-message" *ngIf=" ...

ReactJS - Opt for useRef over useState for props substitution

Presented below is my ImageFallback component, which serves as a backup by displaying an svg image if the original one is not available. export interface ImageProps { srcImage: string; classNames?: string; fallbackImage?: FallbackImages; } const Im ...

Can you explain the distinction between any[] and [] in TypeScript?

Here is an example that successfully works: protected createGroups(sortedItems: Array<TbpeItem>): any[] { let groups: any[] = []; return groups; } However, the second example encounters a TypeScript error: type any[] not assignable to ...

Astro component experiencing script tag malfunction within content collection

I'm trying to create something using a script tag, but for some reason the script doesn't seem to be working properly. Below is my content collection: --- title: Essay Similarity stakeholder: THESIS articleDate: 05 Feb 2023 projectStart: 2022-08 ...

Angular 4: Exploring the Depths of Nested HTTP Requests

I'm struggling to receive a JSON response that contains an array with every declaration, including the user and category information. I currently have a static solution, but I want to implement a dynamic approach and I'm facing difficulties makin ...

I am excited to create a Dynamic Routing system that selects specific elements from an array of objects using Typescript

1. crops-list.component.ts import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-crops-list', templateUrl: './crops-list.component.html' ...

Implementing the binding of components to another component post using forwardRef

I am looking to connect the Title and Body components with the Wrapper component. Previously, my component structure looked like this: import { FC } from 'react'; // binding required components const Title: FC<...> = () => {...} const ...

Running Jest tests with TypeScript involves executing the tests twice: once for TypeScript files and once for JavaScript files

I’ve recently started writing tests using TypeScript and Jest, but I’m running into an issue where the tests are being executed twice – once for the TS files and then again for the compiled JS files. While the TypeScript tests are passing without an ...

Loading a webpack bundled ngModule dynamically to handle a route efficiently

In an effort to make working on our large frontend projects more manageable, we are looking to split them into multiple independently deployed projects. I am attempting to integrate a bundled ngModule to handle a route from within another app. It is crucia ...

Exploring how to iterate through an object to locate a specific value with TypeScript and React

I am looking to hide a button if there is at least one order with status 'ACCEPTED' or 'DONE' in any area or subareas. How can I achieve hiding the "Hide me" menu item when there is at least one area with orders having status 'ACCE ...

Issue with typing in subscription encountered in Typescript RXjs version 6.6.0

Have you attempted using the code snippet below? const data = new Data() data.subscribe({ next: (value) => {}, error: (value) => {}, complete: (value) => {}, }); Encountering this error: Compilation failed. sr ...

Setting up only two input fields side by side in an Angular Form

I'm fairly new to Angular development and currently working on creating a registration form. I need the form to have two columns in a row, with fields like Firstname and Lastname in one row, followed by Phone, Email, Password, and Confirm Password in ...

Utilizing Angular 4 with Ahead-Of-Time compilation in combination with Electron, as well as

I am new to Angular/Typescript and currently developing a cross-platform Desktop application with Electron and Angular 4. My current challenge involves using a Service in different components, but I need this service to be loaded from a separate file based ...

Issue with selecting an individual value in NGRX entity using id

My goal is to retrieve an object by its Id from the entity state using a reducer. Here is the implementation: export interface MessageState extends EntityState<Message> { // additional entities state properties loaded: boolean; loading: boole ...

What is the best way to perform a query in Angular using Firebase Firestore?

I am attempting to execute queries in Angular 6 using Firebase Firestore. I have this code, and I have already installed the package "npm firebase @angularfire" but it is not working: import { Component } from '@angular/core'; import { A ...