I have recently started working with Angular and I am using ngrx to manage the state in my application. However, when I try to compile the code, I encounter an error that says 'Types of parameters 'action' and 'action' are incompatible'. Can someone help me understand why this error is occurring and how can I resolve it?
Error: src/app/shopping-list/store/shoppingList.actions.ts:9:5 - error TS2564: Property 'payload' has no initializer and is not definitely assigned in the constructor.
9 payload: Ingredient;
~~~~~~~
src/app/app.module.ts:25:27 - error TS2322: Type '(state: { ingredients: Ingredient[]; } | undefined, action: AddIngredient) => { ingredients: Ingredient[]; }' is not assignable to type 'ActionReducer<{ ingredients: Ingredient[]; }, Action>'.
Types of parameters 'action' and 'action' are incompatible.
Property 'payload' is missing in type 'Action' but required in type 'AddIngredient'.
25 StoreModule.forRoot({ shoppingList: shoppingListReducer }),
~~~~~~~~~~~~
src/app/shopping-list/store/shoppingList.actions.ts:9:5
9 payload: Ingredient;
~~~~~~~
'payload' is declared here.
This is the content of my shoppingList.actions.ts file.
import { Action } from '@ngrx/store'
import { Ingredient } from '../../shared/ingredient.model';
export const ADD_INGREDIENT = 'ADD_INGREDIENT';
export class AddIngredient implements Action {
readonly type = ADD_INGREDIENT;
payload: Ingredient;
}
And here is the shoppingList.reducer.ts file.
import { Ingredient } from "src/app/shared/ingredient.model";
import * as shoppingListActions from './shoppingList.actions';
const intialState = {
ingredients: [
new Ingredient("Apples", 3),
new Ingredient("Tomatoes", 4)
]
}
export function shoppingListReducer(state = intialState, action: shoppingListActions.AddIngredient) {
switch (action.type) {
case shoppingListActions.ADD_INGREDIENT:
return {
...state,
ingredients: [...state.ingredients, action.payload]
}
default:
return state;
}
}
Finally, this is the content of my app.module.ts file.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRouting } from './app-routing.module';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { StoreModule } from '@ngrx/store';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { SharedModule } from './shared/shared.module';
import { CoreModule } from './core.module';
import { shoppingListReducer } from './shopping-list/store/shoppingLis.reducer';
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
HttpClientModule,
StoreModule.forRoot({ shoppingList: shoppingListReducer }),
AppRouting,
SharedModule,
CoreModule,
],
bootstrap: [AppComponent]
})
export class AppModule { }