@ Ngrx / store:如何查询具有关系的模型

时间:2017-06-02 10:44:27

标签: javascript angularjs redux ngrx ngrx-store

我是一个使用Redux的Angular 2应用程序(使用@ngrx / store),我用这种方式模拟了商店:

{

  modelA: {
    ids: [1, 2],
    entities: { 1: { name: "name modelA 1" },
                2: { name: "name modelA 2" }
              }
  },

  modelB: {
    ids: [5, 8],
    entities: { 5: { name: "name modelB 5" },
                8: { name: "name modelA 8" },
                9: { name: "name modelA 9" }
              }
  } 

}

基本上,我有两种类型的对象:modelA和modelB。现在可以了。 但是我无法找到哪个是在此之间编写关系的最佳方式,表示像modelA这样的东西有很多模型B(一对多)。我可以这样做吗?

modelAmodelB: {
  entities: {
    1: [5],
    2: [8, 9]
  }
}

这是商店的根源,它不是来自&model;' modelA'的孩子。 这可能有用,但我怎么会查询'来自特定型号A的modelB,使用@ngrx / store方法?因为如果我编写一个读取全局状态的选择器函数并从modelAmodelB返回部分状态,那么当我编写函数时,我无法访问其余的状态。例如:

compose(getModelAEntities(number[]), getModelAModelBRelations(modelA_id: number), getModelAModelBState() );

我可以使用Observable.combineLast

查询
Observable
.combineLatest(
  this.store.select('contentContents'),
  this.store.select('contents'),
  (relations: any, contents: any) => {
    return relations.entities[1].map( id => {
      return contents.entities[id]
    })
  }
).subscribe( data => {
  console.log(data);
})

但我不知道这是否正确:每当我更改modelA实体对象(例如添加一个新对象)时,都会调用subscribe(),但输出是相同的,因为两个都不是modelA实体已经改变了它的modelB相关对象。

PS:我可以这样查询

export const getModelAModelBs = (id) => {
  return state => 
    state.select( (s: any) => [s.modelAModelB.entities[id], s.modelB.entities])
    .distinctUntilChanged( (prev, next) => {

      const new_m = (next[0] || []).map( id => {
        return next[1][id];
      });

      const old_m = (next[0] || []).map( id => {
        return prev[1][id];
      });

      return prev[0] === next[0] && (JSON.stringify(new_m) === JSON.stringify(old_m))
    })
    .map( ([ids = [], modelBs]) => ids.map( id => modelBs[id]) );
};

//use the selector
this.store.let(getModelAModelBs(1)).subscribe( data => {
  console.log(data)
})

但我不知道这是否是最佳方法。

1 个答案:

答案 0 :(得分:1)

我在同样的问题上苦苦挣扎,并提出了包装器的解决方案。

请查看ngrx-entity-relationship库:https://www.npmjs.com/package/ngrx-entity-relationship

您可以创建如下选择器:

export const selectUserWithCompany = entityUser(
  entityUserCompany(),
);

然后在商店中使用它

this.store.select(selectUserWithCompany, 'userId');

获得

{
  id: 'userId',
  companyId: 'companyId',
  company: {
    id: 'companyId',
    // ...,
  },
  // ...,
}