在加载其余数据时如何在Angular中预加载一部分数据? [英] How to preload a portion of data in Angular while loading the rest?

查看:99
本文介绍了在加载其余数据时如何在Angular中预加载一部分数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试加载第一页数据并在后台加载整个数据集并显示它时,我以为自己很聪明.我使用了以下代码.

I thought I was smart when I tried to load the first page of data and display it while loading the whole set in the background. I used the following code.

ngOnInit() {
  this.service.getStuff(0, 10)
    .subscribe(suc => this.subset = suc);

  this.service.getStuff()
    .subscribe(suc => this.data = suc);
}

然后,我在API中设置断点,以获取并释放第一个调用,并保持未释放的第二个调用.但是,根据我的浏览器中的网络"标签,两个呼叫均待处理,直到全部完成.

Then, I set the breakpoint in my API fetching and releasing the first call and holding up unreleased the second. However, according to the network tab in my browser, both calls are pending until both are completed.

我是在附近可以进行预加载的地方还是离它很远?

Am I anywhere close to have the pre-load working or is it far, far off?

实际调用是通过通常的 HttpClient 和GET执行的,返回一个可观察的结果.

The actual call is performed the usual HttpClient and a GET, returning an observable.

推荐答案

为此,最好使用一些RxJS运算符.

You'd be better off using some RxJS operator for this.

这将触发两个GET.先到先得.

This will fire both GETs. First come first served.

merge(this.service.getStuff(0, 10), this.service.getStuff()).subscribe(data => {
  // do stuff with data
});

下面,switchMap将使allStuff $仅在initialStuff $发出后才触发. 只有在第一个GET发出后,才会触发第二个GET.

Below, switchMap will make allStuff$ only fire after initialStuff$ has emitted. This will fire the second GET only after the first one emits.

const intialStuff$ = this.service.getStuff(0, 10).pipe(
  share()
);

const allStuff$ = intialStuff$.pipe(
  switchMap(() => this.service.getStuff())
);

intialStuff$.subscribe(...);
allStuff$.subscribe(...)

请注意,由于没有任何请求会阻止渲染,因此您绝对应该使用第一种方法.它将更快地获取所有数据.

Note that since none of requests would block rendering, you should definitely go with the first method. It will fetch all the data faster.

这篇关于在加载其余数据时如何在Angular中预加载一部分数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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