angular - RxJS 扩展减少循环不返回结果

标签 angular rxjs rxjs6

我正在尝试建立一个分页结果列表。我有循环工作,但我可以获得可观察到的结果以发出最终结果。它循环完成但从不发送给订阅者。不确定使用 EMPTY 是否是错误的完成方式,或者是否因为 EMPTY 而没有命中 reduce 并且永远不会触发最后的结果?

getReportsAll(collection: Collection): Observable<PagedResult<ReportView>> {
return Observable.create(observer => {
  this.collectionService.collectionBy(collection)
  const url = this.collectionService.buildUrl(this.reportsUrl)
  const newPage = new PagedResult<ReportView>([], null, null, 0)
  this.getReportPage(url)
    .pipe(
      expand(result => {
        const skip = collection.pageBy.skip + collection.pageBy.top
        collection.pageBy = new PageBy(collection.pageBy.top, skip)
        this.collectionService.collectionBy(collection)
        const nextUrl = this.collectionService.buildUrl(this.reportsUrl)
        const test = result.count >= collection.pageBy.top ? this.getReportPage(nextUrl) : EMPTY
        console.log('test', test)
        return test
      }),
      reduce((next: PagedResult<ReportView>, data: PagedResult<ReportView>, index: number) => {
        next.value = [...next.value, ...data.value]
        next.count = next.value.length
        console.log('next', next, index)
        return next
      }, newPage),
    )
    // .catch(error => observer.error(error))
    .subscribe(results => {
      console.log('results', results)
    })
})

最佳答案

我解决了这个问题,我缺少 takeWhile() 这里是完整的解决方案,以防其他人想做类似的事情。

  getReportsAll(collection: Collection): Observable<PagedResult<ReportView>> {
this.collectionService.collectionBy(collection)
const url = this.collectionService.buildUrl(this.reportsUrl)
const newPage = new PagedResult<ReportView>([], null, null, 0)
return this.getReportPage(url).pipe(
  expand(result => {
    const skip = collection.pageBy.skip + collection.pageBy.top
    collection.pageBy = new PageBy(collection.pageBy.top, skip)
    this.collectionService.collectionBy(collection)
    const nextUrl = this.collectionService.buildUrl(this.reportsUrl)

    return result.count >= collection.pageBy.top ? this.getReportPage(nextUrl) : of(null)
  }),
  takeWhile((value: PagedResult<ReportView> | Observable<void>, index: number) => {
    if (value === null) {
      return false
    }
    return true
  }),
  reduce((next: PagedResult<ReportView>, data: PagedResult<ReportView>, index: number) => {
    next.value = [...next.value, ...data.value]
    next.count = next.value.length
    return next
  }, newPage),
)

关于angular - RxJS 扩展减少循环不返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51605024/

相关文章:

javascript - 如何在包含同步和异步函数的 Observables 的 RxJS 中创建合适的队列

angular - 无法在我的 Angular 4 项目中导入 lodash.add

Angular2 Dart - 在 Angular2 组件中获取文本

performance - 如何衡量 Ionic 3 应用程序的性能?

arrays - 从 Angular 服务获取对象数组

angular - 为每个循环获取 Observable 数据

javascript - 在 ngrx 中的订阅内部进行管道传输

angular - 使用 tap() 而不是 map() RxJS 和 Angular

angular - 在 Angular 8 中,上传时由于 polyfills-es2015 而发生构建错误

typescript - RXJS 和 Socket.io 有什么区别