Silence in Angular NGRX Effects

I am currently utilizing ngrx Effects to send a http call to my server, but for some reason the effect is not triggered. My goal is to initiate the http call when the component loads. I have tried using store.dispatch in ngOnInit, however, nothing seems to happen.

In users.component.ts:

import { Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import * as fromUsersReducer from './states/users.reducer';
import * as UsersActions from './states/users.action';
export class UsersComponent implements OnInit {
  constructor(
    private store: Store<fromUsersReducer.State>,
  ) { }
  ngOnInit() {
    this.store.dispatch(new UsersActions.Load());
  }
}

In users.actions.ts:

export enum UsersActionTypes {
  Load = '[Users] Load',
  LoadSuccess = '[Users] Load Success',
  LoadFail = '[Users] Load Fail',
}    
export class Load implements Action {
  readonly type = UsersActionTypes.Load;
}    
export class LoadSuccess implements Action {
  readonly type = UsersActionTypes.LoadSuccess;    
  constructor(public payload: Users[]) {}
}    
export class LoadFail implements Action {
  readonly type = UsersActionTypes.LoadFail;    
  constructor(public payload: string) {}
}    
export type UsersActions = Load | LoadSuccess | LoadFail;

In users.effects.ts:

@Injectable()
export class UsersEffects {
  constructor(private action$: Actions, private usersService: UsersService) {}

  @Effect()
  loadUsersDetails$ = this.action$.pipe(
    ofType(UsersAction.UsersActionTypes.Load),
    mergeMap((action: UsersAction.Load) =>
      this.usersService.getUsers().pipe(
        map(response => {
          if (response) {
            let users = new Array<Users>();
            console.log(response);
            .........
            return new UsersAction.LoadSuccess(users);
          }
        }),
        catchError(err => of(new UsersAction.LoadFail(err)))
      )
    )
  );
}

In users.reducer.ts:

export interface State extends fromRoot.State {
  users: UsersState;
}
export interface UsersState {
  users: Users[];
}
const getUsersFeatureState = createFeatureSelector<UsersState>('users');
export const getUsersDetails = createSelector(
  getUsersFeatureState,
  state => state.users
);
export const initialState: UsersState = {
  users: [],
};
export function reducer(state = initialState, action: UsersActions) {
  switch (action.type) {
    case UsersActionTypes.LoadSuccess:
      console.log('Users Reducer - Received Full Data for Users: ', action.payload);
      return {
        ...state,
        users: action.payload,
      };
    default:
      return state;
  }
}

In users.module.ts:

@NgModule({
  declarations: [UsersComponent],
  imports: [
    CommonModule,
    SharedModule,
    MaterialModule,
    StoreModule.forFeature('users', reducer),
    EffectsModule.forRoot([UsersEffects])
  ],
  exports: [UsersComponent],
  providers: [UsersService],
  entryComponents: [UsersComponent]
})
export class UsersModule { }

In app.module.ts:

@NgModule({
  declarations: [AppComponent],
  imports: [
    StoreModule.forRoot({}),
    EffectsModule.forRoot([]),
  ],
  ............
})
export class AppModule {}

Any suggestions on what might be causing the issue?

Answer №1

Remember to only use one EffectsModule.forRoot. Consider using the following instead:

  EffectsModule.forFeature([UsersEffects])

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

Angular 5 - Empty array containing objects has a length of zero

In my app.component.ts file, I have an array initialized to load objects in the onInit event: ngOnInit() { this.pages = []; } Within the ngOnInit event, I also have a setInterval method that evaluates an expression every few milliseconds: setInterval(() ...

Angular2 - adding the authentication token to request headers

Within my Angular 2 application, I am faced with the task of authenticating every request by including a token in the header. A service has been set up to handle the creation of request headers and insertion of the token. The dilemma arises from the fact t ...

Having trouble retrieving values from radio buttons in Angular 2 forms

Having trouble displaying the values of radio button inputs in Angular 2 forms. ...

Initial compilation of Angular 2 project with lazy-loaded submodules fails to resolve submodules

I'm working on an Angular 2 project (angular cli 1.3.2) that is structured with multiple modules and lazy loading. In my main module, I have the following code to load sub-modules within my router: { path: 'module2', loadChildren: & ...

Verify whether a web application is equipped with React, Angular, or Vue

Is there an easy way to identify the client-side libraries used by an application if they are minified or compressed? While examining all the JavaScript sent from the server to the client, it can be challenging to determine if one of the top three popular ...

Explore the Attribute and generate a Text-Node using the Renderer

Given the advice against directly accessing the DOM in Angular for various platforms, I am trying to figure out how to achieve the following using Renderer: a) Store the offsetLeft value of $event.target in a variable called left. b) Create a text node wi ...

The component is functioning properly, but it directs to a 404 page when the "**" route is set up

Description I am facing an issue in my Angular 14 application where one of the pages/components is not functioning correctly when I set the "**" route in the `app-routing.module`. Without this configuration, everything works fine, but as soon as I include ...

Issues have been reported regarding the paramMap item consistently returning null when working with Angular 8 routing

I am encountering an issue with Angular 8 where I am trying to fetch some parameters or data from the route but consistently getting empty values. The component resides within a lazy-loaded module called 'message'. app-routing.module.ts: ... { ...

When any part of the page is clicked, the data on the Angular page will automatically

Clicking the mouse anywhere on the page, even in a blank spot, causes the data array to resort itself. I understand that clicking may trigger a view change if an impure pipe is set, but I have not used one. So I am puzzled because my development testing ...

The "library" is encountering errors due to missing dependencies, specifically @angular/material/form-field

I've been working with a shared component library project that has been running smoothly for a while now. Recently, I decided to replace some of the custom components with Angular Material components. However, after adding NgMat to the library project ...

Could you explain the significance of the ^ symbol preceding a software version number?

Considering updating a package in my application, specifically the "@types/react-router-dom" from version "4.3.1" to "5.0.0". However, I'm hesitant as it is a large project and I don't want to risk breaking anything. While reviewing the package. ...

Compiling TypeScript: Using the `as` operator to convert and then destructure an array results in a compilation error, requiring an

I am currently utilizing TypeScript version 2.9.2. There is a static method in a third-party library called URI.js, which is declared as follows: joinPaths(...paths: (string | URI)[]): URI; I have a variable named urlPaths that is defined as urlPaths: s ...

Can a React function component be typed with TypeScript without the need for arrow functions?

Here is my current React component typed in a specific way: import React, { FunctionComponent } from "react"; const HelloWorld : FunctionComponent = () => { return ( <div> Hello </div> ); } export default HelloWorld; I ...

What are some effective strategies for utilizing observables for handling http requests in an Angular application?

In my Angular application, I am retrieving data from APIs. Initially, my code in detail.component.ts looked like this: //code getData() { this.http.get(url1).subscribe(data1 => { /* code: apply certain filter to get a filtered array out */ t ...

Utilizing a background image property within a styled component - Exploring with Typescript and Next.js

How do I implement a `backgroung-image` passed as a `prop` in a styled component on a Typescript/Next.js project? I attempted it in styled.ts type Props = { img?: string } export const Wrapper = styled.div<Props>` width: 300px; height: 300px; ...

In an Angular Material data table, table headers will always be displayed, even if there is no data

When utilizing the Angular material data table to present product-related information with sorting functionality using matSort, I faced an issue. Even when no data is available, the table headers still remained visible due to the [hidden]="!data" ...

Tips for implementing a personalized Circuit Breaker in Node.js that monitors request volume

Currently, I am exploring the most effective way to implement a circuit breaker based on the number of requests served in a Typescript/express application rather than fail percentage. Given that the application is expected to accommodate a large volume of ...

"Angular Chart.js Updates: Keeping Your Charts Up-to-

Have a question regarding the integration of chart.js in an Angular 11 environment. I am working with 2 charts. AppComponent.html: <div class="col-sm"> <canvas id="bl" ></canvas> </div> <div class="col ...

The name 'Queue' cannot be located in Typescript, error code ts(2304)

I'm currently trying to create a private variable of type InnerItem, but I keep encountering the following error: Error: Cannot find name 'Queue'.ts(2304) private savedItems: Queue<InnerItem> = new Queue<InnerItem>(20); Could ...

Retrieving the status of a checkbox using Angular's field binding feature

While using Angular 5.1.1, I am facing an issue where a function is not called correctly when a checkbox changes. This problem seems to occur specifically with the checkbox input type, as it always sends the value "on" to the function even when the checkbo ...