在Angular中读取多个图像 [英] Reading multiple images in Angular

查看:60
本文介绍了在Angular中读取多个图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular,在评论列表中,我想显示评论列表.对于每个评论,我想显示其内容和作者的个人资料图片.我成功地获得了评论列表,但是我以错误的顺序获得了图像列表.我认为这是一个同步问题.

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

推荐答案

在将图像推入数组时,使用Student_id将其推入数组,就像

While pushing images to an array, Push it with student_id, like

this.comments_images.push({id:comment.student_id, img: reader.result}); 

或者更好地将img保留在注释数组本身中,例如

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>

这篇关于在Angular中读取多个图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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