Paopao
Paopao

Reputation: 9

ERROR TypeError: Cannot read property 'file' of undefined in template

I'm trying to insert a picture in profile user component. But there it's showing me a error: that the 'file' is undefined. even the profile picture its showing there. In MySQL the file datatype is MediumBlob(). this is the code in .ts file:

this.userFileServices.getUserPicture(this.userProfile.id).subscribe(data => {
  this.userFile = data;
  console.log(data);

});

and code in .html is:

<img class=" img-circle" src="data:image/png;base64,{{userFile.file}}" 
    width="140" height="140" style="margin-bottom: 1rem;height: 130px;">

the picture is set to profile, I can see it, but there is also this kind of error: ERROR TypeError: Cannot read property 'file' of undefined

Upvotes: 0

Views: 446

Answers (2)

Tim Lepage
Tim Lepage

Reputation: 872

For your second problem: the src of the image should be a trusted url you need to inject in your constructor: private sanitizer: DomSanitizer and then :

this.userFileServices.getUserPicture(this.userProfile.id).subscribe(data => {
      const imageData = 'data:image/png;base64," + data.file;
      this.imageSrc = this.sanitizer.bypassSecurityTrustUrl(imageData);
   });
  })

and then in your html:

<img class=" img-circle" [src]="imageSrc" width="140" height="140" style="margin-bottom: 1rem;height: 130px;">

Upvotes: 4

Jan Deutschl
Jan Deutschl

Reputation: 571

Just change it to {{userFile?.file}} field userFile is undefined before you get your data from the server.

Upvotes: 2

Related Questions