• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

在加载其余数据时在Angular预加载一部分数据?

用户头像
it1352
帮助1

问题说明

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

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.

正确答案

#1

为此,最好使用一些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.

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcgjghc
系列文章
更多 icon
同类精品
更多 icon
继续加载