I'm experiencing issues with my NgRx effects as they are not functioning properly and nothing

I'm facing an issue with my NgRx effects.

Although the application successfully adds to the store, my effects related to the request are not executing. When adding a new car, it should be added to the store and trigger the effects, but nothing is happening. There are no console logs from my effects, no HTTP errors due to incorrect URLs, basically no feedback at all.

Below is my app code:

Reducer

import { Action } from '@ngrx/store';
import * as CarActions from './car.actions';
import { Car } from 'src/models/car.model';

const initialState: Car = {
   brand: '',
   model: ''
};

export function carReducer(state: Car[] = [initialState], action: CarActions.Actions) {

    switch (action.type) {
        case CarActions.ADD_CAR:
            return [...state, action.payload];
        case CarActions.ADD_CAR_FAIL:
            return {
                ...state,
                carError: action.payload,
            };
        default:
            return state;
    }
}

State

import { Car } from './../../models/car.model';

export interface AppState {
  readonly car: Car;
}

Actions

import { Action } from '@ngrx/store';
import { Car } from './../../models/car.model';

export const ADD_CAR       = '[CAR] Add';
export const ADD_CAR_FAIL    = '[CAR] Fail';

export class AddCar implements Action {
    readonly type = ADD_CAR;

    constructor(public payload: Car) {}
}

export class AddCarFail implements Action {
    readonly type = ADD_CAR_FAIL;

    constructor(public payload: string) {}
}

export type Actions = AddCar | AddCarFail;

Effects

import { Actions, Effect, ofType } from '@ngrx/effects';
import * as CarActions from './car.actions';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { switchMap, catchError, map, tap } from 'rxjs/operators';
import { of } from 'rxjs';

@Injectable()
export class CarEffects {
    @Effect()
    carAdd = this.actions$.pipe(
        ofType(CarActions.ADD_CAR),
        switchMap((carData: CarActions.AddCar) => {
            console.log('true');
            return this.http.post('http://myapi.com/api', { brand: carData.payload.brand, model: carData.payload.model }).pipe(map(resData => {
                localStorage.setItem('test', 'asdasdasd');
            }),
                catchError(errorRes => {
                    console.log(errorRes);
                    const errorMessage = 'An unknown error occurred!';
                    if (!errorRes.error || !errorRes.error.error) {
                        return of(new CarActions.AddCarFail(errorMessage));
                    }

                    console.log(errorRes.error.error.message);
                    return of(new CarActions.AddCarFail(errorRes.error.error.message));
                }));
        })
    );

    constructor(
        private actions$: Actions,
        private http: HttpClient) { }
}

App.Module.ts

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

import { AppComponent } from './app.component';
import { CarComponent } from './car/car.component';
import { StoreModule } from '@ngrx/store';
import { carReducer } from './car/car.reducer';
import { HttpClientModule } from '@angular/common/http';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';


@NgModule({
  declarations: [
    AppComponent,
    CarComponent
  ],
  imports: [
    BrowserModule,
    StoreModule.forRoot({ car: carReducer }),
    HttpClientModule,
    StoreDevtoolsModule.instrument({
      maxAge: 5
    })
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Do you think my implementation of NgRx in the code is correct?

Answer №1

You missed including the Effect in your Angular module

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

import { AppComponent } from './app.component';
import { CarComponent } from './car/car.component';
import { StoreModule } from '@ngrx/store';
import { carReducer } from './car/car.reducer';
import { HttpClientModule } from '@angular/common/http';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { EffectsModule } from '@ngrx/effects';
import { CarEffects } from './car/car.effects';


@NgModule({
  declarations: [
    AppComponent,
    CarComponent
  ],
  imports: [
    BrowserModule,
    StoreModule.forRoot({ car: carReducer }),
    HttpClientModule,
    EffectsModule.forRoot([CarEffects]),
    StoreDevtoolsModule.instrument({
      maxAge: 5
    })
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Answer №2

To properly incorporate your effects, it is necessary to import the EffectsModule.

In your app.module.ts file, you should include the following:

import {CarEffects} from 'path/to/careffects';

@NgModule({
  declarations: [
    AppComponent,
    CarComponent
  ],
  imports: [
    BrowserModule,
    StoreModule.forRoot({ car: carReducer }),
    HttpClientModule,
    StoreDevtoolsModule.instrument({
      maxAge: 5
    }),
    //                               ADD THIS BELOW !!
    EffectsModule.forRoot(
      [CarEffects]
    )
  ],
  providers: [],
  bootstrap: [AppComponent]
})

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

Utilizing PrimeNG radio buttons for selecting multiple items simultaneously

While dynamically creating multiple radio buttons using *ngFor, I am facing an issue where I can select multiple items from the UI. Below is my code snippet: <div class="p-col-12"> <p>Question Type</p> <div *ngFor ...

Encountering a Module Missing Error Upon Heroku Deployment

Encountering an error while deploying my app from Github to Heroku: ERROR in ./src/Index.tsx Module not found: Error: Can't resolve './ConfigureStore' in '/app/src' @ ./src/Index.tsx 9:23-50 Appears to be a Typescript issu ...

Utilizing a string as an index in TypeScript

Struggling with the following code snippet: interface IStudentType { [key: `${Students}`]: IStudent | IStudentMaths| IStudentPhysics } The error message received is TS1268: An index signature parameter type must be 'string', &apos ...

In Ionic 2, trying to access the IONIC_ENV variable consistently results in it being undefined

Does anyone know how to access the IONIC_ENV variable in order to switch between using the API URL for production and development environments? Every time I try to check it, it returns undefined. process.env.IONIC_ENV I might need to run or add another c ...

Creating a mapping for a dynamic array of generic types while preserving the connection between their values

In my code, I have a factory function that generates a custom on() event listener tailored to specific event types allowed for user listening. These events are defined with types, each containing an eventName and data (which is the emitted event data). My ...

Switch up the item's background in the dropdown list within Kendo UI Angular

Looking for a solution to highlight text and change background color in a dropdown list based on certain conditions. I searched the official Kendo forum without success. Any guidance or suggestions on how to resolve this issue would be greatly appreciate ...

Assigning a value to the <Style> tag in an Angular 2 template

I am currently working with a component that uses a template from an HTML file. The template structure looks like this: <div class="abc"></div> <style> .abc { background-color: {{myColor}} } </style> My question ...

What is the best way to automatically determine the type of a callback value based on a property within the same object?

As I work on developing a DataGrid component, my goal is to create a feature where the columns can be inferred based on the type of object in each row. The usage scenario for this component would look like: const users: User[] = [ {name: 'John&apos ...

`Easily toggle between checking and unchecking a checkbox in Angular 2 using the spacebar

I am currently exploring Angular 2 and am attempting to create a checkbox functionality where the checkbox is checked and unchecked by hitting the spacebar. Below is the code used for the checkbox in my component.html- <md-checkbox #checkBox (keyup)=" ...

Exploring the power of async/await and promise in TypeScript

I'm puzzled as to why the return type string in this method is showing up as a red error: exportPageAsText(pageNumber: number): string { (async () => { const text = await this.pdfViewerService.getPageAsText(pageNumber); ...

Displaying a div component in React and Typescript upon clicking an element

I've been working on a to-do list project using React and TypeScript. In order to display my completed tasks, I have added a "done" button to the DOM that triggers a function when clicked. Initially, I attempted to use a useState hook in the function ...

Optimal method for establishing a variable when utilizing the @Input decorator in Angular

Imagine we have a Definition called User: export interface User { username: string; email: string; password: string; } Now, in a higher-level component, we aim to send an instance of User to a child component: <child-element [user]="in ...

Angular RxJs Error: Unable to access property within an undefined object

Apologies if this question is unclear, as I am a beginner in the MEAN stack. I've been attempting to display an array from an express middleware on an angular frontend. However, despite everything appearing to work fine and compiling without errors, I ...

The npm installation process may not always properly install required dependencies within an Angular project

I encountered some issues with my Angular project while running npm install. Despite seeing errors and missing dependencies in the node_modules folder, none of the error messages provided a clear explanation. The log output displays deprecation warnings an ...

Angular: Error when TypeScript object returns an array object value

I have encountered a strange issue where the array value returned as [object Set] when I console log it. It's unclear whether this problem is occurring in the component or the service, but the object values are not being displayed. This issue arises ...

Remove all input fields within an HTML file using a TypeScript method implemented in an Angular 2 component

Within my Angular project, there are several input elements in the HTML file that are not enclosed within a form tag. I am looking to create a function in the TypeScript file that will clear all of these inputs. I attempted to utilize ViewChild, but it a ...

Exploring Ionic 4 with Angular Router

Presently, I am working on developing an application using the latest beta version 4 of Ionic and implementing the tabs layout. I am still trying to grasp how the navigation works with the new Angular router. This is my app-routing.module.ts: import { N ...

Can a type be designed to allow the second argument to be typed according to the type of the first argument?

In my preference, I would rather have the type of the second argument inferred from the type of the first argument instead of being explicitly specified as a type argument. This way, it can be passed without the need for explicit typing. I typically defin ...

What is the best way to repeatedly subscribe to an observable?

Within the ngOnInit() function of my Angular application, I am subscribing to an Observable in the following manner: ngOnInit() { this.loadArtistTable(); } loadArtistTable(): void { this._artistService.getArtists().subscribe( (artistL ...

What causes the unexpected behavior of the rxjs share operator when used with an observable in a service?

I attempted to utilize the rxjs share operator in two distinct manners. Implementing it in the component Component: constructor() { const obs1 = interval(1000).pipe( tap(x => console.log('processing in comp1')), map(x => x ...