typescript Rxjs合并将省略的观测值组合到数组中

shyt4zoc  于 7个月前  发布在  TypeScript
关注(0)|答案(1)|浏览(67)

我有下面的代码,它可以组装要在导航栏中显示的项目。
对于某些项,它调用API来获取额外的信息,并将该信息添加到subtitle字段。
我想把它重新组合成一个Observable<NavItem[]>,这样它就可以使用异步管道渲染了。
目前它在我调用ops.toArray()之前记录每个NavItem。但是在ops.toArray()之后的日志调用永远不会返回.
有没有更好的RXJS方法将这些项目重新组合成Observable<NavItem[]>

import * as ops from 'rxjs/operators';

navItem$: Observable<NavItem[]> = null

this.navItem$ = this.store.pipe(
  select(fromRoute.selectLastUrls),
  ops.map((d) => {
    // Initial construction of NavItems
  }),
  ops.tap((i) => console.log(i)), // Prints an array of 5 NavItems as expected
  ops.mergeAll(),
  ops.mergeMap((i) =>
    iif(
      () => i.listItem,
      // Call the API for some list items (To add subtitle detail)
      this.backendService.find({ title: [i.title] }).pipe(
        ops.map((found) => ({...i, subtitle: found.items[0].info,})),),
        of(i),
    ),
  ),
  ops.tap((i) => console.log(i)), // This expected 1 NavItem per log line (with data appended from the API calls)
  ops.toArray(),
  ops.tap((i) => console.log(i)) // This line never logs
);

字符串

mwyxok5s

mwyxok5s1#

在你的例子中,toArray等待整个流完成,然后它会把所有的元素收集到一个数组中。
要将此逻辑仅应用于group,您必须将运算符放在更深的一个级别上。像这样:

this.navItem$ = this.store.pipe(
  select(fromRoute.selectLastUrls),
  ops.map((d) => {
    // Initial construction of NavItems
  }),
  ops.tap((i) => console.log(i)), // Prints an array of 5 NavItems as expected
  ops.switchMap(arr => from(arr).pipe(
     ops.mergeMap((i) =>
       iif(
        () => i.listItem,
         // Call the API for some list items (To add subtitle detail)
         this.backendService.find({ title: [i.title] }).pipe(
           ops.map((found) => ({...i, subtitle: found.items[0].info,})),),
         of(i),
       ),
     ),
     ops.tap((i) => console.log(i)), // This expected 1 NavItem per log line (with data appended from the API calls)
     ops.toArray(),
    ))
  
  ops.tap((i) => console.log(i)) // This line will log arrays now
);

字符串
我还要提到的是,不推荐使用import * as ops from 'rxjs/operators';,因为这样所有的操作符都会进入bundle。如果你只是独立导入每个操作符,那么所有未使用的操作符都会被树摇走,结果bundle应该更小。

相关问题