0

I'm trying to grab a blob image from my API and insert it as an img src.

This is my service:

 public download(fileName: string) {
   this.http.get('http://x.x.x.x:4000/api/' + fileName, { responseType: 'blob'}).subscribe(res => {
    console.log( "TEST 1: " + window.URL.createObjectURL(res) ) ;
    return window.URL.createObjectURL(res);
   });
 }

And this is my .ts file:

export class FileListComponent {

 public pictureSrc;
 public fileList$: Observable<string[]> = this.fileService.list();

 constructor(private fileService: FileService) { }

 public download(fileName: string):  void {
  console.log ("TEST 2: " + this.fileService.download(fileName));
  this.pictureSrc = this.fileService.download(fileName);
 }

and my .html:

   <img src="{{ pictureSrc }}">

When I run this, it grabs the right blob url in TEST 1 but TEST 2 is 'undefined' and then so is my image src.

Any idea why the url wont travel from my service to my .ts file?

Thanks.

glog
  • 809
  • 2
  • 9
  • 19

1 Answers1

0

Yes, because of returning the URL inside subscription. Try this:

public download(fileName: string) {
    return this.http.get('http://x.x.x.x:4000/api/' + fileName, { responseType: 'blob'}).pipe(
        map(res => window.URL.createObjectURL(res)));
}

Additionally, here's a similar question: How to return value inside subscribe Angular 4