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

时间:2020-02-07 21:24:06

标签: angular httpclient

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

{ 
  "sammy" : {
    "username"  : "SammyShark",
    "location"  : "Indian Ocean",
    "online"    : true,
    "followers" : 987
  },
  "jesse" : {
    "username"  : "JesseOctopus",
    "location"  : "Pacific Ocean",
    "online"    : false,
    "followers" : 432
  },
  "drew" : {
    "username"  : "DrewSquid",
    "location"  : "Atlantic Ocean",
    "online"    : false,
    "followers" : 321
  },
  "jamie" : {
    "username"  : "JamieMantisShrimp",
    "location"  : "Pacific Ocean",
    "online"    : true,
    "followers" : 654
  }
}

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

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

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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

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

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

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));
 }
}