简体   繁体   English

Angular - 来自 API 的 blob 的绑定图像 url

[英]Angular - Binding image url from blob from API

I'm trying to grab a blob image from my API and insert it as an img src.我正在尝试从我的 API 中获取 blob 图像并将其作为 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:这是 my.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);
 }

and my.html:和我的.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.当我运行它时,它会在 TEST 1 中获取正确的 blob url,但 TEST 2 是“未定义的”,然后我的图像 src 也是如此。

Any idea why the url wont travel from my service to my.ts file?知道为什么 url 不会从我的服务传送到 my.ts 文件吗?

Thanks.谢谢。

Yes, because of returning the URL inside subscription.是的,因为返回 URL 内部订阅。 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此外,还有一个类似的问题: How to return value inside subscribe Angular 4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM