如何在加载其余数据的同时预加载 Angular 中的一部分数据?

How to preload a portion of data in Angular while loading the rest?

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

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

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

然后,我在我的 API 中设置断点获取并释放第一个调用并阻止未释放的第二个调用。但是,根据我浏览器中的网络选项卡,这两个调用都是 待定,直到它们都完成。

我离预加载工作很近还是很远?

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

你最好为此使用一些 RxJS 运算符。

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

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

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

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

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

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

请注意,由于 none 的请求会阻止呈现,因此您绝对应该使用第一种方法。它将更快地获取所有数据。

Angular HttpClients get() 应该每次都返回一个新的 Observable,并且不会表现出您描述的行为。

这完全取决于this.service.getStuff()的实现。如果实现看起来像下面这样,它应该在每次调用时返回一个新的 Observable 并使其独立于任何其他 call/subscribe.

doStuff() {
    return this.http.get('someUrl');
}

Here's an example of the two observable calls working independent of each other - 我拖延时间来帮助演示。当您 运行 执行此操作时,第一个调用将完成并在第二个调用之前呈现。

具有初始化逻辑的组件:

ngOnInit(){
this.myService.doSomething('todos/1', 100)
  .subscribe(resp => {
    this.first = resp;
  });

this.myService.doSomething('comments', 1500)
  .subscribe(resp => {
    this.second = resp;
  })
}

示例服务:

@Injectable()
export class MyService {
  constructor(private http: HttpClient){}

  doSomething(route: string, withDelay?: number) {
    return this.http.get('https://jsonplaceholder.typicode.com/' + route)
      .pipe(delay(withDelay));
 }
}