如何创建选择器以按ID从ngrx商店选择项目 [英] How to create selector to select an item by id from ngrx store

查看:14
本文介绍了如何创建选择器以按ID从ngrx商店选择项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了ngrx store的documentation关于选择器的内容,需要弄清楚如何创建一个选择器以便按项ID选择一项。当我从selectAllItems选择器中获得所有物品时,我已经可以将此作为商店订阅的一部分,但我需要弄清楚如何从商店中的物品列表中选择特定的物品。我的主要原因是createSelector提供了我喜欢从中受益的性能提升。

以下是我的代码:

import { AppState, Item } from '../../shared/models/index';
import { createSelector } from '@ngrx/store';

export const selectItems = (state: AppState) => state.eventsState;

export const selectAllItems = createSelector(selectItems, (allItems: { items: Item[] }) => {
  if (allItems && allItems.items) {
   return allItems.items.filter((item: Item) => (!item.active && !item.closed));
  } else {
    return allItems.items;
  }
});

然后在我的控制器中,我按ID进行筛选,以获得所需的项目:

this.store.select(selectors.selectAllItems)
  .filter(data => data !== null)
  .subscribe(allItems => {
    this.item = allItems.filter(item => {
      return item.id === this.navParams.data.id;
    });
  });

我希望能够为该特定项目创建选择器,并按如下方式使用它:

this.store.select(selectors.selectItemById(this.navParams.data.id))
  .filter(data => data !== null)
  .subscribe(selectedItem => {
    this.item = selectedItem;
  });

如有任何帮助,将不胜感激。

推荐答案

经过一番研究,我自己的问题解决了。我使用工厂函数获得所需的selectItemById选择器。这是我的新选择器:

import { AppState, Item } from '../../shared/models/index';
import { createSelector } from '@ngrx/store';

export const selectItems = (state: AppState) => state.eventsState.items;

export const getItemById = (id) => createSelector(selectItems, (allItems) => {
  if (allItems) {
    return allItems.find(item => {
      return item.itemId === id;
    });
  } else {
    return {};
  }
});

然后我在我的控制器中所要做的就是调用这个选择器,并向它传递一个所需商品的ID,以便将该商品从商店中取出:

import * as selectors from '../../app/store/selectors';

this.store.select(selectors.getItemById(id))
  .subscribe((item) => {
    this.item = item;
  });

这篇关于如何创建选择器以按ID从ngrx商店选择项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆