@Ngrx/store: how to query models with relationships

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-12 13:35:24

问题


I an Angular 2 app using Redux (with @ngrx/store), I have modeled the store this way:

{

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

}

Basically, I have 2 types of objects: modelA and modelB. This is ok for now. But I can't find which is the best way to write a relationship between then, representing something like modelA has many modelB (one-to-many). Can I do something like this?

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

This is in the root of the store, it's not a child from 'modelA'. This might work, but how then would I 'query' the modelB from a specific modelA, using @ngrx/store methods? Because if I write a selector function that reads the global state and returns the partial state from modelAmodelB, I don't have access to the rest of the state when I compose my functions. Example:

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

I can query this using 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);
})

But I don't know if this is right: anytime I change modelA entities object (adding a new one, for example), the subscribe() is called, but the output is the same, because neither modelA entity has changed nor its modelB related objects.

PS: I could do the query this way

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

But I don't know if this is the best approach.

来源:https://stackoverflow.com/questions/44327028/ngrx-store-how-to-query-models-with-relationships

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!