在 Angular 中读取多张图片
Reading multiple images in Angular
我正在使用Angular,在评论列表中,我想显示评论列表。对于每条评论,我都想显示其内容和作者的头像。我成功地获得了评论列表,但是我以错误的顺序获得了图像列表。我觉得是同步的问题
您可以在下面看到函数的代码。
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;
}
)
});
}
在将图像推送到数组时,使用 student_id 推送它,例如
this.comments_images.push({id:comment.student_id, img: reader.result});
或者更好地将 img 保留在注释数组本身中,例如
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;
}
}
);
});
所以每条评论都会有自己的图片,不会出错。你可以像
一样轻松阅读它
<div *ngFor="let comment of comments">
<img src="{{comment.image}}" /> <span>{{comment.message}}</span>
</div>
我正在使用Angular,在评论列表中,我想显示评论列表。对于每条评论,我都想显示其内容和作者的头像。我成功地获得了评论列表,但是我以错误的顺序获得了图像列表。我觉得是同步的问题
您可以在下面看到函数的代码。
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;
}
)
});
}
在将图像推送到数组时,使用 student_id 推送它,例如
this.comments_images.push({id:comment.student_id, img: reader.result});
或者更好地将 img 保留在注释数组本身中,例如
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;
}
}
);
});
所以每条评论都会有自己的图片,不会出错。你可以像
一样轻松阅读它<div *ngFor="let comment of comments">
<img src="{{comment.image}}" /> <span>{{comment.message}}</span>
</div>