Error: Unable to find provider for Store in Angular 9 AuthService Guard

I have been working on implementing an Auth guard with Angular 9, but I encountered an ERROR in the browser console:

ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(SampleModule)[AuthGuard -> Store -> Store -> Store -> Store]: NullInjectorError: No provider for Store! NullInjectorError: R3InjectorError(SampleModule)[AuthGuard -> Store -> Store -> Store -> Store]: NullInjectorError: No provider for Store! at NullInjector.get (core.js:1050) at R3Injector.get (core.js:16521) at R3Injector.get (core.js:16521) at R3Injector.get (core.js:16521) at NgModuleRef$1.get (core.js:35539) at R3Injector.get (core.js:16521) at injectInjectorOnly (core.js:905) at Module.ɵɵinject (core.js:915) at Object.AuthGuard_Factory [as factory] (auth.guard.ts:17) at R3Injector.hydrate (core.js:16747) at resolvePromise (zone-evergreen.js:793) at resolvePromise (zone-evergreen.js:752) at zone-evergreen.js:854 at ZoneDelegate.invokeTask (zone-evergreen.js:400) at Object.onInvokeTask (core.js:40744) at ZoneDelegate.invokeTask (zone-evergreen.js:399) at Zone.runTask (zone-evergreen.js:168) at drainMicroTaskQueue (zone-evergreen.js:570)

Below is the code for the Guard:

import {
  CanActivate,
  CanActivateChild,
  ActivatedRouteSnapshot,
  RouterStateSnapshot
} from '@angular/router'
import { Store } from '@ngrx/store'
import { AppState } from '../auth.store/states/app.state'
import { AuthService } from '../auth.services/auth.services'
import { AuthActions } from '../auth.store/actions/auth.actions'

@Injectable({
    providedIn: 'root'
})

export class AuthGuard implements CanActivate, CanActivateChild {
  constructor(private store$: Store<AppState>,
              private authService: AuthService) {
  }

This is my Sample module

import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { TranslateModule } from '@ngx-translate/core';

import { SampleComponent } from './sample.component';
import { AuthGuard } from 'app/auth.app/auth.guards/auth.guard';

const routes = [
    {
        path     : 'sample',
        component: SampleComponent,
        canActivate : [AuthGuard]
    }
];

@NgModule({
    declarations: [
        SampleComponent
    ],
    imports     : [
        RouterModule.forChild(routes),

        TranslateModule,
    ],

    providers:[
        AuthGuard
    ],

    exports     : [
        SampleComponent
    ]
})

export class SampleModule
{
}

And this is my app module

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { RouterModule, Routes } from '@angular/router';
import { MatMomentDateModule } from '@angular/material-moment-adapter';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { TranslateModule } from '@ngx-translate/core';
import 'hammerjs';
import { AppComponent } from 'app/app.component';
import { LayoutModule } from 'app/layout/layout.module';

const appRoutes: Routes = [
    {
        path        : '',
        loadChildren: () => import('./auth.app/auth.module').then(m => m.AuthModule)
    },    
    {
        path        : '',
        loadChildren: () => import('./main/sample/sample.module').then(m => m.SampleModule)
    }
];

@NgModule({
    declarations: [
        AppComponent,
    ],
    imports     : [
        BrowserModule,
        BrowserAnimationsModule,
        HttpClientModule,
        RouterModule.forRoot(appRoutes),

        TranslateModule.forRoot(),

        // Material moment date module
        MatMomentDateModule,

        // Material
        MatButtonModule,
        MatIconModule,

        // App modules
        LayoutModule,
        // SampleModule,
    ],
    bootstrap   : [
        AppComponent
    ]
})
export class AppModule
{
}

Answer №1

To import the store, you need to include it in the imports list:

imports: [
 StoreModule.forRoot(...)
]

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

Display an image in an Angular application using a secure URL

I am trying to return an image using a blob request in Angular and display it in the HTML. I have implemented the following code: <img [src]="ImageUrl"/> This is the TypeScript code I am using: private src$ = new BehaviorSubject(this.Url); data ...

Utilize interface as a field type within a mongoose Schema

I am currently working with typescript and mongoose. I have defined an interface like this: interface Task { taskid: Boolean; description: Boolean; } My goal is to create a schema where one of the fields contains an array of Tasks: const employeeSche ...

Changing the generic type's constraint type in TypeScript to have more flexibility

I have developed a utility type named DataType that takes in a parameter T restricted to the type keyof MyObject. When the key exists in MyObject, DataType will return the property type from MyObject; otherwise, it will simply return T. interface MyObject ...

`Why isn't GetServerSideProps being triggered for a nested page in Next.js when using Typescript?

I have been working on a page located at /article/[id] where I am trying to fetch an article based on the id using getServerSideProps. However, it seems that getServerSideProps is not being called at all as none of my console logs are appearing. Upon navi ...

Are SCSS style sheets being properly included in ng-packagr packaging?

I've been working on developing an Angular component library, packaging the modules for easy NPM installation. However, I took the old-school approach instead of using the CLI like Angular 6 recommends. Despite that, my components function properly wh ...

The Angular 6 test command using npm has encountered a failure

I've been encountering a disconnect error while attempting to run Angular test cases. With over 1500 test cases written, it appears that the sheer volume may be causing this issue. Is there a way to resolve the disconnect error when running such a lar ...

Step-by-step instructions for deactivating a specific FormControl within a FormArray

I've created a form that includes custom details: this.myform= new FormGroup({ ... customDetails: new FormArray([]), }); get customDetailsFormArray() { return this.shippingLocationDetailsUpdateForm.get( 'customDetails' ) as Form ...

Challenge encountered with TypeScript integration in the controller

I am currently in the process of converting a website from VB to C# and incorporating TypeScript. I have successfully managed to send the data to the controller. However, instead of redirecting to the next page, the controller redirects back to the same pa ...

Tips for preventing HTTP calls within chained Angular subscriptionsHere are some strategies to prevent

I am faced with a scenario where I have to call an HTTP service to retrieve data, and then based on that data, I need to immediately make another HTTP request. Typically, I would use pipe along with switchMap to accomplish this task efficiently. However, t ...

Generating a fresh object from an existing object by incorporating updated values using Angular and Ionic version 3

Currently, I am actively working on an Ionic 3 project that utilizes Angular framework. Within my project, I have a JSON object called 'person' which consists of data fields such as name, job, and home. One feature in my app is an Ionic toggle b ...

Troubleshooting Clarifai object error while invoking "model.predict" within Angular Framework

I've been attempting to utilize Clarifai's color API to extract the different colors present in an image. Unfortunately, I am encountering challenges when trying to call the API, as it consistently returns empty objects. Below is the snippet of ...

Using Next.js, it is not possible to use absolute imports within SASS

Having trouble utilizing @/ imports within my scss files. The variables I need are stored in src/styles/_variables.scss Here is my tsconfig.json: { "compilerOptions": { "lib": ["dom", "dom.iterable", "esnext"], "baseUrl": ".", "allowJs": tr ...

Showcasing a badge counter within a tab

I am trying to implement a counter badge that shows the number of current packages uploaded next to its tab. However, I noticed that the badge only appears when I click on the tab. Ideally, it should automatically update and display the counter without nee ...

Tips for correctly specifying the types when developing a wrapper hook for useQuery

I've encountered some difficulties while migrating my current react project to typescript, specifically with the useQuery wrappers that are already established. During the migration process, I came across this specific file: import { UseQueryOptions, ...

Continuously encountering CORS errors despite activating them, using .NET Core in conjunction with an Angular client

I recently encountered a CORS issue in my .NET Core 3.0 Web API project despite having enabled CORS in the startup file. Here's how I configured it: ConfigureService services.AddCors(options => { options.AddPolicy("AllowOrigin", builder => b ...

What is the best way to iterate through an array within a class in Angular 2?

I am trying to iterate over an array named data, within another array containing 'champions'. Can anyone provide the correct syntax for this? I can successfully loop through all the champions within my IChampion interface, but I'm having tro ...

Mistakes that occur while trying to expand a base class to implement CRUD functionality

Creating a base class in TypeScript for a node.js application to be extended by all entities/objects for CRUD operations is my current challenge. The base class implementation looks like this: export class Base { Model: any; constructor(modelName ...

What could be causing the NodeJs cluster module to be malfunctioning?

Currently, I am in the process of constructing an express server and have been exploring the concept of scaling NodeJS applications. Upon my research, one of the initial things that caught my eye was the built-in cluster module which allows for leveraging ...

How exactly does the 'this' type in TypeScript determine its own type inferences?

When working with TypeScript, I wanted to use the this keyword to type certain properties of my class. However, I encountered a problem that I couldn't figure out how to solve. What I was trying to achieve is something like this: export class Animal{ ...

Troubleshooting Next.js Route Redirect Failure to Origin URL

I'm currently facing a challenge in my Next.js project where I have a layout component nested inside the app directory. Within this layout component, there's a client-side navbar component that includes a logout button. The goal is to redirect th ...