I have started learning NgRx framework in Angular. Getting below error while fetching the data from sample API.
'ERROR TypeError: Cannot read properties of undefined (reading 'products')'
I don't have feature modules. So, I have created a selector like this
export const selectProductState = createFeatureSelector<fromProduct.ProductState>(
fromProduct.customerFeatureKey
);
export const getProductState = createSelector(
selectProductState,
(state: fromProduct.ProductState) => state
);
reducer code
import { createReducer, on } from "@ngrx/store";
import { Product } from "../product";
import * as ProductAction from './product.actions';
export interface ProductState {
products: Product[];
error: string;
}
export const customerFeatureKey = 'products';
export const initialState: ProductState = {
products: [],
error: ''
};
export const productReducer = createReducer<ProductState>(
initialState,
on(ProductAction.loadProductsSuccess, (state, action): ProductState => {
return {
...state,
products: action.products,
error: ''
};
}),
on(ProductAction.loadProductsFailure, (state, action): ProductState => {
return {
...state,
products: [],
error: action.error
};
})
);
effects code
@Injectable()
export class ProductEffects {
constructor(private actions$: Actions, private productService: ProductService) { }
loadProducts$ = createEffect((): any => {
return this.actions$.pipe(
ofType(ProductAction.loadProducts),
mergeMap(()=> this.productService.getProducts().pipe(
map(products =>
ProductAction.loadProductsSuccess({products})
)
))
)
})
}
I don't understand where am I doing mistake. Can anyone help me.