我有以下可观察的数组:
const stages = [
{Id: 1, Name: "First stage", RoleId: 71},
{Id: 2, Name: "Second stage", RoleId: 72},
{Id: 3, Name: "Third stage", RoleId: 73}];
const roles = [
{Id: 71, Name: "Stuff", Key: "STF"},
{Id: 72, Name: "Manager", Key: "MGR"},
{Id: 73, Name: "CEO", Key: "CEO"}];
所以我有"MGR"
键,并且想观察stages
,其中RoleId
等于经理的角色。
它们是两个可观察到的:阶段和角色。我已经了解了combineLatest
方法,这可能对我有帮助,但我不知道如何过滤合并结果。
const filteredStages = stages.combineLatest(roles, (s, r) => ({
s: s,
r: r
}))
.filter(x => ?);
获得过滤阶段的正确方法是什么?
答案 0 :(得分:0)
如果role.Id
不会被更改:
stages.filter(stage => stage.RoleId === 72)
如果以后可能更改role.Id
:
const manager = roles.find(role => role.Key === "MGR");
stages.filter(stage => stage.RoleId === manager.Id)
答案 1 :(得分:0)
您需要从Roles $流中获取数组中的所有ID,然后将所有具有匹配ID的阶段的map切换到stage $流:
return roles$.pipe(
switchMap(roles => {
let ids = roles.filter(role => role.Key === 'MGR').map(role => role.Id);
return stage$.pipe(
filter(stage => ids.indexOf(stage.Id) > -1),
);
})
);
答案 2 :(得分:0)
这是使用Rxjs版本5语法
我认为创建另一个要过滤的角色的观察对象是明智的。下面,我通过按Key属性进行过滤来完成此操作。
const stages$ = Observable.of([
{Id: 1, Name: "First stage", RoleId: 71},
{Id: 2, Name: "Second stage", RoleId: 72},
{Id: 3, Name: "Third stage", RoleId: 73}]);
const roles$ = Observable.of([
{Id: 71, Name: "Stuff", Key: "STF"},
{Id: 72, Name: "Manager", Key: "MGR"},
{Id: 73, Name: "CEO", Key: "CEO"}];
const selectedRole$ = roles$.filter((roles) => {
return roles.filter(r => r.Key === "MGR");
});
const filteredStages$ = Observable.combineLatest(
stages$,
selectedRole$,
(stagesArr, role) => {
return stagesArr.filter(s => s.Id === role.Id)
})
.subscribe((filteredStages) => console.log('stages', filteredStages);
答案 3 :(得分:-2)
所以最后我解决了我的问题。我通过使用map
函数来做到这一点。
const key = 'MGR';
const filteredStages = stages.combineLatest(roles,
(s, r) => ({
s,
r
})).map(x => {
const managerRole = x.r.find(role => role.LookupKey === key);
return x.s.filter(stage => stage.RoleId !== managerRole.Id);
});