简体   繁体   English

Angular2中重复的HTTP请求

[英]Repeated HTTP requests in Angular2

Say, I have more than 100 items in the database and the exact number not known. 说,我在数据库中有100多个项目,确切的数目未知。 My back-end API will give me desired number of items if I provide the start item ID and the number of items required. 如果我提供起始项目ID和所需的项目数,我的后端API将为我提供所需的项目数。 Item ID is starting from 0 and increasing by 1. 商品ID从0开始,以1递增。

I want to fetch them batch by batch (for example 10 items per batch) to process in the client side. 我想分批提取它们(例如每批10个项目)以在客户端进行处理。 After finishing processing one batch, I want to fetch the next batch. 完成一批的处理后,我要提取下一批。

What is the best way to achieve this using RxJS in my Angular 2 project? 在我的Angular 2项目中使用RxJS实现此目标的最佳方法是什么?

I think you'll want to look into Subject s in RxJS. 我想你会想看看Subject S IN RxJS。 You can use one in an Angular2 Service to fetch the next page of results and push them to your UI using the subject's .next(<value>) api. 您可以在Angular2服务中使用其中一个来获取结果的下一页,并使用主题的.next(<value>) API将其推送到您的UI中。 Then expose a public observable to your components that they will subscribe to (or use an async pipe in a template) so that they can show the results. 然后将公开的可观察对象公开给您将要订阅的组件(或在模板中使用异步管道),以便它们可以显示结果。

The service that has the Subject can keep track of the number that you're at so it can have a fetchNextPage type of method on it that can be called to get the next batch of results pushed through the Subject and into your UI. 具有主题的服务可以跟踪您所处的号码,因此可以在其上使用fetchNextPage类型的方法,可以调用该方法来获取通过主题进入用户界面的下一批结果。

So something like this: 所以像这样:

Injectable Service which has a Subject, probably methods like fetch and fetchNextPage to gather data, as well as an exposed results or something that is the Subject's .asObservable() 具有主题的可注入服务,可能是诸如fetchfetchNextPage类的方法来收集数据,以及公开的results或主题的.asObservable()

Component that gets the service injected, and then sets up a subscription to the service's results Observable. 注入服务的组件,然后为该服务的results Observable设置订阅。 Call the service's fetch in your ngOnInit of your component, then when your UI deems it necessary, call fetchNextPage on the service to load more data. 在组件的ngOnInit中调用服务的fetch ,然后在用户界面认为有必要时,在服务上调用fetchNextPage以加载更多数据。

Should work okay. 应该可以吧。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM