在Angular 9中,为什么我的订阅是顺序加载而不是并行加载? [英] In Angular 9, why are my subscriptions getting loaded sequentially instead of in parallel?

查看:69
本文介绍了在Angular 9中,为什么我的订阅是顺序加载而不是并行加载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular9.我想加载一系列对象,每个对象都有图像数据.我想先加载所有对象,然后再加载图像数据.我的component.ts文件ngOnInit中有这个文件...

I'm using Angular 9. I want to load a series of objects, each of which has image data. I would like to load all the objects, first, and then load the image data after. I have this in my component.ts file ngOnInit ...

  ngOnInit(): void {

    this.authService.getAllinLibrary().subscribe((res: any[]) => { 
      this.results = res;
      ...

      for (let i = 0; i < results.length; i++) {
        this.getTheImage(res[i].Id, i);
      }
    });



  getTheImage(imageId: number, index: number) {
    this.authService.getPersonImage(imageId).subscribe(data => {
      this.createImageFromBlob(data, index);
      this.isImageLoadingArr[index] = false;
      console.log("loaded image:" + index);
    }, error => {
      this.isImageLoadingArr[index] = false;
      console.log(error);
    });
  }
  

我像这样在我的组件中显示数据

    I display the data in my component like so

             <mat-grid-tile *ngFor="let person of results; let i = index;" class="animated flipInX">

                  <div class="image-background">
                      <img [src]="images[i]"
                        alt="" width="100%">
                      

似乎并非所有并发运行加载图像数据的调用.也就是说,每次我都会收到日志消息

It seems that all the calls to load the image data are not being run concurrently. That is, every time, I get the log messages

loaded image: 0
loaded image: 1
loaded image: 2
loaded image: 3
loaded image: 4
     ....
 

按顺序打印,使我相信调用不会并发执行.如何修改我拥有的内容,以使获取图像源的调用并发执行,而不是一次执行?

printed in sequential orde, leading me to believe the calls aren't getting executed concurrently. How do I modify what I have so that the calls to get the image sources get executed concurrently and not one at a time?

推荐答案

我认为最好的方法是实现forkJoin Rxjs规范:

I think the best appraoch is to implement forkJoin Rxjs specifications :

     this.authService.getAllinLibrary().subscribe((res: any[]) => { 
          this.results = res;
          ...
     let observableBatch = [];

  results .forEach(( componentarray, key ) => {
    observableBatch.push( this.getTheImage(res[key ].Id, key); );
  });
 

      const getImagesObservable= forkJoin(observableBatch );
       
    getImagesObservable.subscribe({
     next: value => your Implementation Here
     complete: () => console.log('This is how it ends!'),
    });

});

这篇关于在Angular 9中,为什么我的订阅是顺序加载而不是并行加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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