NgRx:从存储中获取数据,但未定义

时间:2018-10-16 17:27:48

标签: angular typescript ngrx ngrx-store ngrx-effects

尊敬的Stackoverflow社区。

我是NgRx的新手,正试图找出它是如何工作的。我创建了一个应用-基于Angular 6,Firebase和NgRx的简单商店清单。

我在集合中添加了两个名为Product的项目,并尝试通过ngrx模式获取它们。似乎我做得很好-我已经在GET_PRODUCTS_SUCCESS中将项目作为有效负载获取,但是我无法将它们放入视图中显示,产品未定义。我尝试通过两种方式进行操作:

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

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

第二种方式,我得到了整个商店... 下面的代码。

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-获取并显示所有产品

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);
    });

  }

}

如果您发现我做错了-不要害羞告诉我。 我真的需要你的帮助。谢谢。

1 个答案:

答案 0 :(得分:3)

好吧,我发现了...

我看着我还能如何从存储请求数据。我找到了一种方法,在我的应用中,它看起来像

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

然后我进入控制台对象:

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

WTF?什么消息?我进行了全局搜索,发现我在app.module.ts中实现了我的reducer:

StoreModule.forRoot({ message: ProductReducer }),

好的。因此,我在reducers文件夹中创建了index.ts并导出了以下的reducer:

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
};

现在在app.module.ts中,它导入为

    StoreModule.forRoot(reducers),

现在此代码运行良好:

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