【问题标题】:How to get data in chunks from an API using rxjs interval and stop when there is no data left如何使用 rxjs 间隔从 API 中获取数据块并在没有数据时停止
【发布时间】:2021-03-09 22:37:34
【问题描述】:

我正在尝试按时分块加载数据。为此,我正在使用你的方法。

此函数从我用来模拟 api 数据的 json 对象加载数据

 getScrollingData(startIndex, endIndex){
    if(this.items.data.length>endIndex){
      return of(this.items.data.slice(startIndex, endIndex));
    }else{
      return of(null)
    }
  }

下面的 getData 方法用于每两秒发送一次请求

getData(){
const secondsCounter = interval(2000); 
return secondsCounter
.pipe(
  flatMap((res) => {
    if(res!=null)
     return this.mimicApiService.getScrollingData(res, res+10)
            .takeUntil(v => v != null)// this causes error
  }),
  
  
)

}

在组件的 ngOnInit 中,我订阅了 getData 以将该数据加载到要在屏幕上显示的数组中

data = [];
ngOnInit() {
  this.dataService.getData().subscribe((res)=>{
    this.data = [...this.data, ...res];
  });
}

问题

  1. 我从 takeUntil 收到错误 Argument of type '(v: any) => boolean' is not assignable to parameter of type 'Observable<any>'。你能说出为什么会这样吗?

【问题讨论】:

    标签: angular rxjs rxjs6


    【解决方案1】:

    你使用了错误的操作符,takeUntil 想要一个 observable,一旦 observable 发出就会停止接收。

    您需要的是 takeWhile,它更适合您的用例:

    takeWhile(v => v != null)
    

    这里是doc

    编辑: 如果您还想在getScrollingData 没有返回更多数据时停止间隔,您可以执行以下操作:

    getData() {
      const stopInterval = new Subject();
      const secondsCounter = interval(2000)
        .pipe(takeUntil(stopInterval));
      return secondsCounter
        .pipe(
          flatMap((res) => {
            if (res != null)
              return this.getScrollingData(res, res + 2)
          }),
          takeWhile(v => {
            if (v == null) {
              stopInterval.next();
              return false;
            }
            return true;
          }))
    }
    

    一旦我们从 stopInterval 发出,takeUntil 的间隔就会触发。

    【讨论】:

    • 这会阻止内部 Observable 运行,但外部 Observable(间隔)仍在计数
    猜你喜欢
    • 1970-01-01
    • 2019-10-04
    • 1970-01-01
    • 2018-04-08
    • 1970-01-01
    • 2021-12-10
    • 2016-12-21
    • 2020-01-31
    • 1970-01-01
    相关资源
    最近更新 更多