0

I'm using a forEach to set images to each item, but the function doesn't work right and I can't figure it out right now.

ngOnInit() {
    this.workerId = parseInt(window.location.pathname.split('/')[2], 10);
    if (this.competences.length > 0) {
      this.filter.competences = this.competences;
    }
    this.mechanismService.getMechanisms(this.filter).subscribe(
      data => {
        this.allMechanisms = data;
        this.allMechanisms.forEach(mech => {
          mech.pictureSource = this.getImageFromService(mech.picture.id);
        });
        console.log(this.allMechanisms);
      }
    );
  }

getImageFromService(fileId) {
    this.userService.getProfilePicture(fileId).subscribe(data => {
      console.log(this.createImageFromBlob(data));
      return this.createImageFromBlob(data);
    }, error => {
      console.log(error);
    });
  }

createImageFromBlob(image: Blob) {
    const reader = new FileReader();
    reader.addEventListener('load', () => {
      console.log(reader.result);
      return reader.result;
    }, false);
    if (image) {
      reader.readAsDataURL(image);
    }
  }

So the console.log(reader.result); logs the right data, but from console.log(this.createImageFromBlob(data)); it's undefined.

How would I fix or work around this?

eixcs
  • 1,957
  • 4
  • 15
  • 37
  • 1
    I'm not going to answer this, but a good tip: for line 3: (if this.competences.length > 0) well you can write it like if (this.competences.length) {...} as 0 is a falsy value, and positive numbers are truthy values. You don't need to check if its greater than 0 – Sweet Chilly Philly May 31 '19 at 07:28
  • 1
    You can find some answers over here (https://stackoverflow.com/questions/55447803/angular-subscribe-within-subscribe/55447947#55447947) I have previously answered a question similar to this – wentjun May 31 '19 at 07:31

0 Answers0