问题
I'm using Angular, in a comments list, I want to display the list of comments. For every comment, I want to display its content and the profile image of its author. I get the list of comments successfully, but I get the list of images in a wrong order. I think it's a problem of synchronization.
You can see below the code of the function.
comments;
comments_images=[];
get_comments(){
let promise = new Promise((resolve, reject) => {
this.myService.course_comments(this.course.id)
.toPromise().then(
res => {
this.comments=res;
this.comments.forEach((comment)=> {
this.myService.student_image(comment.student_id).subscribe(
res2=>{
const reader = new FileReader();
reader.readAsDataURL(res2);
reader.onloadend = ()=> {
this.comments_images.push(reader.result);
}
}
);
});
resolve();
return promise;
}
)
});
}
回答1:
While pushing images to an array, Push it with student_id, like
this.comments_images.push({id:comment.student_id, img: reader.result});
or better keep img in comments array itself like
this.comments.forEach((comment)=> {
this.myService.student_image(comment.student_id).subscribe(
res2=>{
const reader = new FileReader();
reader.readAsDataURL(res2);
reader.onloadend = ()=> {
comment.images = reader.result;
}
}
);
});
So each comment will have their image with no mistake. You can easily read it like
<div *ngFor="let comment of comments">
<img src="{{comment.image}}" /> <span>{{comment.message}}</span>
</div>
来源:https://stackoverflow.com/questions/57324672/reading-multiple-images-in-angular