首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >可观察到的溪流-一对多和多对一

可观察到的溪流-一对多和多对一
EN

Stack Overflow用户
提问于 2020-10-17 02:00:02
回答 1查看 89关注 0票数 1

当项目可以存在于不同的模块中时,如何存储的列表?

to items还是Multi to items?我假设会有很多不同的模块来存储项目,这些模块越多,我就越想离开一个状态。

一州

代码语言:javascript
复制
class Item {
  id: number;
  name: string;
  location: "equipment" | "magazine" | "shop"  // | and other in future...
}

class AppState {
  items: Item[];
}

const getItems = (store: Store): Observable<Item[]> => {
  return store.select((appStore: AppStore) => appStore.items);
}

const getItemsInEquipment = (store: Store): Observable<Item[]> => {
  const items$: Observable<Item[]> = getItems(store);
  return items$.pipe(
    map(items => items.filter(item => item.location === "equipment"))
  );
}

const getItemsInMagazine = (store: Store): Observable<Item[]> => {
  const items$: Observable<Item[]> = getItems(store);
  return items$.pipe(
    map(items => items.filter(item => item.location === "magazine"))
  );
}

const getItemsInShop = (store: Store): Observable<Item[]> => {
  const items$: Observable<Item[]> = getItems(store);
  return items$.pipe(
    map(items => items.filter(item => item.location === "shop"))
  );
}

或者..。

多状态

代码语言:javascript
复制
class Item {
  id: number;
  name: string;
}

class AppState {
  itemsInEquipment: Item[];
  itemsInMagazine: Item[];
  itemsInShop: Item[];
  // | and other in future...
}

const getItemsInEquipment = (store: Store): Observable<Item[]> => {
  return store.select((appStore: AppStore) => appStore.itemsInEquipment);
}

const getItemsInMagazine = (store: Store): Observable<Item[]> => {
  return store.select((appStore: AppStore) => appStore.itemsInMagazine);
}

const getItemsInShop = (store: Store): Observable<Item[]> => {
  return store.select((appStore: AppStore) => appStore.itemsInShop);
}

const getItems = (store: Store): Observable<Item[]> => {
  const itemsInEquipment$: Observable<Item[]> = getItemsInEquipment(store);
  const itemsInMagazine$:  Observable<Item[]> = getItemsInMagazine(store);
  const itemsInShop$:      Observable<Item[]> = getItemsInShop(store);
  return combineLatest([itemsInEquipment$, itemsInMagazine$, itemsInShop$]);
}

这两种方法的优缺点是什么?

EN

回答 1

Stack Overflow用户

发布于 2020-10-17 08:56:52

我建议采取另一种方法。例如,在NgRx中,我们将为所有Items设置一个单一的实体状态,然后将Items的In数组存储在每个列表中。NGXS实验室有一个实体状态适配器,值得一试。

基本上,所有的Items都存储在一个对象中,其中键是每个Itemid字段。

代码语言:javascript
复制
itemEntities: {
  itemId1: Item,
  itemId2: Item,
  itemId3: Item
}

这允许直接查找,并防止因Array操作而造成的性能损失。

然后,您的每个itemsInEquipmentitemsInStore等都是简单的ids数组,允许您从实体状态获取它们。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64398362

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档