我有两个可观察阵列类型Observable<MyType>
的
export interface MyType{
title: string;
id: string;
other: [];
}
我想附加属性exists
添加到第一阵列并将其设置为true
如果产品存在第二阵列中:
const combined$ = combineLatest(this.first$, this.second$);
this.output$ = combined.pipe(
map((x, y) => {
return x.map(a => {
a.title = a.title;
a.id = a.id;
a.other = a.other;
a.exists = y.find(b => b.id === a.id )
});
})
);
始终让[...undefined]
结果,如果订阅了output
观察到this.output$.subscribe(console.log);
任何想法如何解决?
在您的代码段你有,你从combinedLatest rxjs运营商为combined$
,那么过渡这个问题,所以当把它作为combined
下一行,我认为是不正确,或只是一个翻译错误结果设置一个错字。 (不管,必须指出来嘿嘿)
接着,操作者combineLatest
返回所有观测值的数组。因此,你可以用解构的map
操作中很容易地从所有观测的最新值。
下面是最后的代码:
const combined$ = combineLatest(this.first$, this.second$);
this.output$ = combined.pipe(
map(([x, y]) => {
return x.map(a => {
a.title = a.title;
a.id = a.id;
a.other = a.other;
a.exists = y.find(b => b.id === a.id )
});
})
);
在原始代码中,你基本上传递值作为x
的阵列。
我认为组合发送一个值,它是单独的值的阵列。这里y
将是不确定的。
使用([X,Y])来解构里面映射中的值,然后再试一次。合并$也有你错过了一个错字。而find
可以some
代替,以更好地代表逻辑,并返回一个布尔
此外,当您使用x.map
你在逻辑映射错阵列。
const combined$ = combineLatest(this.first$, this.second$);
this.output$ = combined$.pipe(
map(([x, y]) => {
return x.map(a => {
a.title = a.title;
a.id = a.id;
a.other = a.other;
a.exists = y.some(b => b.id === a.id )
});
})
);