Angular - 从 API 的 blob 中绑定图像 url

Angular - Binding image url from blob from API

我正在尝试从我的 API 中抓取一个 blob 图像并将其作为 img src 插入。

这是我的服务:

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

这是我的 .ts 文件:

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

和我的.html:

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

当我 运行 这样做时,它在 TEST 1 中抓取了正确的 blob url 但 TEST 2 是 'undefined' 然后我的图像 src 也是如此。

知道为什么 url 不会从我的服务传送到我的 .ts 文件吗?

谢谢。

是的,因为返回了 URL 内部订阅。 试试这个:

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

此外,还有一个类似的问题: