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

Struggling to implement the Pick utility type alongside the React useState hook

Can anyone explain why I am unable to utilize the Pick utility type in order to select a property from my interface and apply it to type my component's state? This is what my interface looks like: export interface IBooking { ... propertyId: strin ...

What are the different ways to customize the appearance of embedded Power BI reports?

Recently, I developed a website that integrates PowerBI embedded features. For the mobile version of the site, I am working on adjusting the layout to center the reports with a margin-left style. Below are the configuration parameters I have set up: set ...

Troubleshoot: Issue with binding data from DynamicComponentLoader in Angular 2 template

My implementation involves the utilization of DynamicComponentLoader and is based on the Angular2 API Guide. https://angular.io/docs/ts/latest/api/core/DynamicComponentLoader-class.html The code structure I have set up looks like this: import {Page} fro ...

How do I inform Jest that spaces should be recognized as spaces?

Here is some code snippet for you to ponder: import { getLocale } from './locale'; export const euro = (priceData: number): string => { const priceFormatter = new Intl.NumberFormat(getLocale(), { style: 'currency', currenc ...

What is the best way to shift focus to the next input field once the character limit has been reached, especially when the input is contained

My challenge lies in having six input fields arranged side by side in a single row: In my component.html file: onDigitInput(event: any) { let element; if (event.code !== 'Backspace') element = event.srcElement.nextElementSibling; consol ...

Exploring Angular 4's Capabilities: Navigating a Multi-Dimensional Array

I am currently working with a multi-dimensional array that has two keys, and it is structured as follows: user: any = {}; // The index is incremented within a for loop to add values to the user object (this part is functioning correctly) this.user[index++ ...

Typed NextJs navigation to a specific route

<Link href="/about"> <a>About Us</a> </Link> Is there a way to ensure type safety with NextJs links? Currently, it is challenging to restructure the Link component as it is just a string. I stumbled upon this repos ...

The parameter type 'Object' cannot be assigned to the parameter type 'JSON' in the HttpClient GET method

Hey there! Currently, I'm deep into developing an Angular 6 + Flask application and I've encountered a bit of a snag: Error TS2345: Argument of type 'Object' is not assignable to parameter of type 'JSON'. This issue arises w ...

Experimenting with axios.create() instance using jest

I have attempted multiple solutions for this task. I am trying to test an axios instance API call without using any libraries like jest-axios-mock, moaxios, or msw. I believe it is possible, as I have successfully tested simple axios calls (axios.get / axi ...

Using RxJs: switchMap conditionally based on the emitted value being empty

Below is the code snippet I am currently dealing with: const id = 1; // id = 2 of([{id: 1, name: 'abc'}]).pipe( map(items => items.find(item => item.id === id)), switchMap(item => item ? of(item) : this.makeHttp ...

Tips for showing a Dialog box in reference to multiple rows in a table

Objective: Retrieve data and showcase it in a dialog box using the button located in the Button column. Essentially, clicking on one of the buttons will display the corresponding data in the dialog. Challenge: Currently, I can only extract hardcoded s ...

Is it possible for prettier to substitute var with let?

One of the tools I utilize to automatically format my Typescript code is prettier. My goal is to find out if there is a way to have prettier replace all instances of 'var' with 'let' during the formatting process. Below is the script I ...

What is the best method for comparing arrays of objects in TypeScript for optimal efficiency?

Two different APIs are sending me arrays of order objects. I need to check if both arrays have the same number of orders and if the values of these orders match as well. An order object looks like this: class Order { id: number; coupon: Coupon; customer ...

How can I limit a type parameter to only be a specific subset of another type in TypeScript?

In my app, I define a type that includes all the services available, as shown below: type Services = { service0: () => string; service1: () => string; } Now, I want to create a function that can accept a type which is a subset of the Service ...

Using Angular (along with Typescript) to showcase JSON data

I previously shared this query, but unfortunately, I didn't receive many helpful responses I have a JSON file that holds the following dataset: [{ "ID": 1030980, "Component": "Glikoza (Gluk)", "Result": "16", "Date": "20.10.2018" } ...

How to integrate a chips feature in Angular 4 using Typescript

Struggling to incorporate a chips component into my Angular web application, which comprises Typescript, HTML, and CSS files. After grappling with this for weeks without success, I have yet to find the right solution. To review my current code, you can a ...

Dependency type ContextElementDependency does not have a module factory available

As I make changes to the structure of my Angular 4 app with lazy loaded modules, I am encountering an error when running: ng build The error message displayed is: Error: No module factory available for dependency type: ContextElementDependency This e ...

Guide to building an interface for an object containing a nested array

While working on my Angular/TypeScript project, I encountered a challenge in processing a GET request to retrieve objects from an integration account. Here is a snippet of the response data: { "value": [ { "properties": { ...

Encountering the issue "Unable to define properties of undefined" during Angular unit testing tasks

When attempting to write a unit test case for a dropdown, an error is encountered: TypeError: Cannot set properties of undefined (setting 'ReferralCodes') .spec.ts it("should update the action selecting a value from category drop down", ...

Check for a rapid return if the function ends up returning null in JavaScript

Is there a way to make this code more concise? const result = getResult(); if (!result) { return; } // Work with result I have several instances of this code in my project and I'm looking for a simpler solution like: const result = getResult() ...