Reading multiple images in Angular

风流意气都作罢 提交于 2021-01-29 13:15:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!