问题
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?
回答1:
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!'),
});
});
来源:https://stackoverflow.com/questions/64771410/in-angular-9-why-are-my-subscriptions-getting-loaded-sequentially-instead-of-in