Rxjs:基于条件的递归Http调用 [英] Rxjs: Recursive Http calls based on condition

查看:81
本文介绍了Rxjs:基于条件的递归Http调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下命令通过提供固定数量的记录来检索列表.在下面的例子中,它返回 100 条记录(我传递了 pageIndex 值,应该在每个请求中增加它以获得下 100 条记录):

I retrieve a list using the following command by giving a fixed number of record. In the folowing example, it returns 100 records (I pass the pageIndex value and it should be increased in every request in order to get the next 100 record):

this.employeeService.list(1, 100).toPromise().then(data => {
    this.employees = data.items;
});

数据中有一个名为 isComplete 的标志,如果 data.isComplete 值为 false.在 Angular 中使用 Rxjs 执行此操作的正确方法是什么?有一些方法,例如递归订阅等,但似乎不适合这种情况.

There is a flag in the data called isComplete and I want to make the same Http call to the same list method if the data.isComplete value is false. What is a proper approach to perform this using Rxjs in Angular? There are some approaches e.g. recursive subscription etc, but not seems to be good for this scenario.

推荐答案

一个可能的解决方案:

您可能想要扩大和缩小:

A Possible Solution:

You probably want expand and reduce:

我假设页面索引从 0 开始,您在 'expand' 之前开始的页面索引必须比您的服务的第一页索引小 1.

I'm assuming page index starts at 0, the page index that you start with before 'expand' must be 1 less than the first page index from your service.

of({
  isComplete: false,
  pageIndex: -1,
  items: []
}).pipe(
  expand(data => this.employeeService.list(data.pageIndex+1, 100).pipe(
    map(newData => ({...newData, pageIndex: data.pageIndex+1}))
  )),
  takeWhile(data => !(data.isComplete === true), true),
  map(data => data.items),
  reduce((acc, items) => ([...acc, ...items]))
).subscribe(res => {
  this.employees = res;
});

关于承诺的简短说明:

observableStream.toPromise().then(LAMBDA);

大致相当于

observableStream.pipe(last()).subscribe(LAMBDA);

last 等待源竞争并且只发出最终值.这会删除流中的所有其他值.

last waits for the source to compete and only emits the final value. This drops all other values in the stream.

许多第一次使用 Observables 和 Promises 的人倾向于认为它更像:

many people who first work with Observables and Promises tend to assume it works more like:

observableStream.pipe(first()).subscribe(LAMBDA);

以便它采用第一个值,然后尽快使用该值解析 Promise.事实上,情况并非如此.

so that it takes the first value, then resolves the Promise with that value ASAP. This is, in fact, not the case.

一般来说,坚持其中之一是明智的.Observable 是 Promise 的超集.缺少期望 promise 的第三方库,应该永远需要将 Observable 转换为 Promise.

In general, it is wise to stick with one or the other. Observable are a super-set of Promises. Short of third-party libraries expecting promises, there should never be a need to convert an Observable to Promise.

这篇关于Rxjs:基于条件的递归Http调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆