问题描述
有代码:
ngOnInit(): void {
[this.newReleaseNotes$,this.readReleaseNotes$] = partition(this.getReleaseNotes$(),({ id }: ReleaseNoteInterface) =>
this.releaseNotesService.readReleaseNotes.includes(id),);
}
private getReleaseNotes$(): Observable<ReleaseNoteInterface[]> {
return forkJoin(this.releaseNotes.map((releaseNoteId: string) => this.releaseNotesService.fetchReleaseNoteById$(releaseNoteId)));
}
错误TS2345:类型'({{id}:ReleaseNoteInterface)=>布尔值'的参数无法分配给类型'((value:ReleaseNoteInterface [],index)的参数 :number)=>布尔值”。 [0]参数“ __0”和“值”的类型不兼容。 [0]类型“ ReleaseNoteInterface []”缺少类型“ ReleaseNoteInterface”的以下属性:ID,类型,重要性,现状以及另外8个。
this.releaseNotesService.fetchReleaseNoteById $方法向服务器发出请求并返回Observable<ReleaseNoteInterface>
如何正确使用分区运算符解决我的问题?
解决方法
D47
发出其内部可观察值的数组,因此NA
期望类型为forkJoin
,而不是类型为partition
。
因此您的ReleaseNoteInterface[]
必须在该数组上进行操作:
ReleaseNoteInterface
这将创建两个可观察的流,一个流中数组中的任何id都满足条件,另一个流中数组中的任何id不满足条件。怀疑这就是您想要的。
partition
用于将可观察流分成2个流。尽管 partition(this.getReleaseNotes$(),(releaseNotes: ReleaseNoteInterface[]) =>
// unclear what to do with the array here?
releaseNotes.some(({id}) => this.releaseNotesService.readReleaseNotes.includes(id))
);
是一个较高阶的可观测量,用于将多个可观测量组合为一个,而partition
定义上只发射一次,并且一旦所有内部观测完成,它将发射所有内部可观测量的一个数组。因此,在forkJoin
上使用forkJoin
是不合逻辑的,因为存在partition
来拆分多个排放流,并且forkJoin
只能观察到一个排放。
您可能想做的是这样:
partition
这为您提供了两个观察值,两个都是发布说明数组,一个包含满足条件的项目,另一个包含不满足条件的项目。
还有其他逻辑方法可以进行此设置,例如只有一个符合接口forkJoin
的可观察对象,然后使用ngOnInit(): void {
const sharedNotes$ = this.getReleaseNotes$(); // get the sahred
this.newReleaseNotes$ = sharedNotes$.pipe( // map and filter the array
map(releaseNotes => releaseNotes.filter(({id}) => this.releaseNotesService.readReleaseNotes.includes(id)))
)
this.readReleaseNotes$ = sharedNotes$.pipe( // map and filter the array
map(releaseNotes => releaseNotes.filter(({id}) => !this.releaseNotesService.readReleaseNotes.includes(id)))
)
}
private getReleaseNotes$(): Observable<ReleaseNoteInterface[]> {
return forkJoin(this.releaseNotes.map((releaseNoteId: string) => this.releaseNotesService.fetchReleaseNoteById$(releaseNoteId))).pipe(
share() // share it to avoid multiple calls
);
}
运算符将其转换为该可观测对象。
@ bryan60,感谢您的解释!做了一些不同的事情:
ngOnInit(): void {
this.newReleaseNotes$ = this.getReleaseNotes$(this.releaseNotes.filter((id: string) => !this.releaseNotesService.readReleaseNotes.includes(id)));
this.readReleaseNotes$ = this.getReleaseNotes$(this.releaseNotes.filter((id: string) => this.releaseNotesService.readReleaseNotes.includes(id)));
}
private getReleaseNotes$(releaseNotesIds: string[]): Observable<ReleaseNoteInterface[]> {
return forkJoin(releaseNotesIds.map((releaseNoteId: string) => this.releaseNotesService.fetchReleaseNoteById$(releaseNoteId)));
}
最初,我只是想使用partion
函数来解决此问题。
也许可以选择用其他forkJoin
可以代替的partion
吗?