gpt4 book ai didi

javascript - @Ngrx/存储 : how to query models with relationships

转载 作者:行者123 更新时间:2023-12-03 16:27:41 25 4
gpt4 key购买 nike

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

{

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的东西有很多modelB(一对多)。我可以做这样的事情吗?
modelAmodelB: {
entities: {
1: [5],
2: [8, 9]
}
}

这是商店的根目录,它不是来自“modelA”的 child 。
这可能有效,但是我将如何使用@ngrx/store 方法从特定模型A“查询”模型B?因为如果我编写一个读取全局状态并从 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)
})

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

最佳答案

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

请查看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',
// ...,
},
// ...,
}

关于javascript - @Ngrx/存储 : how to query models with relationships,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44327028/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com