NgRx: Get data from store but it's undefined

hofshteyn picture hofshteyn · Oct 16, 2018 · Viewed 7.9k times · Source

dear Stackoverflow Community.

I'm new in NgRx and trying to find out how does it works. I create an app - simple Shop List based on Angular 6, Firebase and NgRx.

I added a couple of items in collection called Product and trying to fetch them via ngrx patterns. Seems I did all good - I have fetched items as payload in GET_PRODUCTS_SUCCESS but I can't put them into the view to display, products are undefined. I tried to do in two ways:

this.store.select(getProducts).subscribe(products => {
  console.log('products', products); // undefined
});

and

 this.products = this.store.select(getProducts); // Store

In second way I just get a whole Store... Code below.

product.actions.ts

import { Action } from '@ngrx/store';
import { Product } from '../../models/product.model';

export const GET_PRODUCTS = 'Get_products';
export const GET_PRODUCTS_SUCCESS = 'Get_products_success';

export class GetProducts implements Action {
  readonly type = GET_PRODUCTS;
  constructor(public payload = '') {}
}

export class GetProductsSuccess implements Action {
  readonly type = GET_PRODUCTS_SUCCESS;
  constructor(public payload?: Product[]) {}
}

export type Actions = GetProducts | GetProductsSuccess;

product.reducer.ts

import { Product } from '../../models/product.model';
import * as productAction from './products.action';

export interface State {
  products: Product[];
  loading: boolean;
}

export const initialState: State = {
  products: [],
  loading: false,
};

export function ProductsReducer(state: State = initialState, action: productAction.Actions) {

  switch (action.type) {
    case productAction.GET_PRODUCTS:
      return {...state, loading: true};

    case productAction.GET_PRODUCTS_SUCCESS:
      const test = {...state, products: action.payload, loading: false};
      console.log("test", test);
      return test;

    default:
        return state;
  }
}

enter image description here

product.effects.ts

import { Injectable } from '@angular/core';
import { Action } from '@ngrx/store';
import { Effect, Actions } from '@ngrx/effects';
import { AngularFirestore } from '@angular/fire/firestore';

import { Product } from '../../models/product.model';
import * as productAction from './products.action';

import { Observable, of } from 'rxjs';
import { switchMap, map, mergeMap } from 'rxjs/operators';


@Injectable()
export class ProductEffects {

  constructor(private actions$: Actions, private db: AngularFirestore) {}

  @Effect()
  getProducts: Observable<Action> = this.actions$
    .ofType(productAction.GET_PRODUCTS).pipe(
      switchMap(() => {
        return this.db.collection<Product>('products').valueChanges()
        .pipe(
          map((payload) => {
            return {
              type: 'Get_products_success',
              payload: payload
            };
          })
        );
      })
    );
}

product.selector.ts

import { createSelector } from '@ngrx/store';

import { State } from './products.reducer';
import { Product } from '../../models/product.model';

export function getState(state: State): State {
    return state;
}

export function fetchProducts(state: State): Product[] {
    return state.products;
}

export const getProducts = createSelector(getState, fetchProducts);

list.component.ts - get and display all products

import { Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import { Product } from '../../models/product.model';
import * as productActions from '../../store/products/products.action';
import { State } from '../../store/products/products.reducer';
import { getProducts } from '../../store/products/products.selector';

import { Observable } from 'rxjs';

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.scss']
})
export class ListComponent implements OnInit {

  products: Observable<Product[]>;

  constructor(private store: Store<State>) {}

  ngOnInit() {
    this.store.dispatch(new productActions.GetProducts);
    this.store.select(getProducts).subscribe(products => {
      console.log('products', products);
    });

  }

}

If you noticed that I'm doing something wrong - don't shy to tell me. I really need your help. Thanks.

Answer

hofshteyn picture hofshteyn · Oct 17, 2018

I found out

I looked that how else I can make a request my data from store. I found one way, in context of my app it looks like:

 this.store.select(state => state).subscribe(data => {
  console.log('data', data);
});

And I get in console the object:

{ message: { Products: Array[3], loading: false } }

What does this message mean? I made a global search and saw that I implemented my reducer in app.module.ts as:

StoreModule.forRoot({ message: ProductReducer }),

So I created a index.ts in reducers folder and export a reducer bellow:

import { ActionReducerMap } from '@ngrx/store';

import * as fromProducts from './products.reducer';

export interface AppState {
    products: fromProducts.ProductState;
}

export const reducers: ActionReducerMap<AppState> = {
    products: fromProducts.productsReducer
};

And now in app.module.ts it imports as:

    StoreModule.forRoot(reducers),

and now this code is working well:

this.store.select(getProducts).subscribe(products => {
  console.log('products', products);
});