【问题标题】:RxJS Expand Reduce Loop not returning resultRxJS展开减少循环不返回结果
【发布时间】:2019-01-07 08:33:50
【问题描述】:

我正在尝试建立一个分页结果列表。我有循环工作,但我可以让 observable 发出最终结果。它循环完成,但从不发送到订阅。不确定使用 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)
    })
})

}

【问题讨论】:

标签: angular rxjs rxjs6


【解决方案1】:

我解决了这个我错过了 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),
)

}

【讨论】:

  • 你还删除了那个很混乱的Observable.create(observer =&gt; ....
  • 是的,抱歉,我不需要它,因为我在其他地方调用它,但它只是一个用于创建 observable 的包装器
猜你喜欢
  • 2014-04-21
  • 1970-01-01
  • 2021-06-05
  • 1970-01-01
  • 2011-08-18
  • 1970-01-01
  • 2017-03-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多