代码之家  ›  专栏  ›  技术社区  ›  avi.elkharrat

Angular 5 http从后端获取图像

  •  2
  • avi.elkharrat  · 技术社区  · 7 年前

    我有一个角度5项目。

    我需要在UI中显示从后端获取的图像(例如,我想在上面的工具栏中显示用户的头像,就像上面的SO工具栏中一样)。

    后端是一个REST服务器,在某个端点上调用时提供图像服务。

    我似乎无法从后端获取图像。我确信后端可以正常工作。

    我已尝试做以下工作(基于此 article ):

    这是我的服务 image.service.ts (锅炉板已拆除)

    getImage(url: string): Observable<Blob> {
      return this.httpClient.get(`${url}`, {responseType: 'blob'})
    }
    

    这是我的成分 image.component.ts

    @Component({
      selector: 'app-image',
      templateUrl: './image.component.html',
      styleUrls: ['./image.component.css']
    })
    export class ImageComponent implements OnInit {
      @ViewChild('myImage') image: ElementRef
    
      constructor(private imageService: ImageService) {}
    
      ngOnInit() {
        this.getMyImage('http://my-super-host:3000/images/super-hero.png')
      }
    
      getMyImage(url: string): void {
        this.imageService.getImage(url)
          .subscribe(response => this.image.nativeElement.src = window.URL.createObjectURL(response))
      }
    }
    

    最后,我的 image.component.html

    <img #myImage>
    

    在浏览器控制台中,会显示一条错误消息

    ERROR TypeError: _this.image is undefined
    

    此解决方案不起作用。我错过了什么?

    2 回复  |  直到 7 年前
        1
  •  1
  •   avi.elkharrat    7 年前

    添加简单

    <img src={{url}}>
    

    成功了。

    从那时起,您可以添加 *ngIf ,则, class ,则, alt 。。。根据需要。

        2
  •  0
  •   user2367418    4 年前

    其他人提出的另一种稍有不同的解决方案,请参见:

    [ https://medium.com/techinpieces/blobs-with-http-post-aand-angular-5-a-short-story-993084811af4][1]

    基于此,我编写了使用Angular 7的代码,其中一些代码如下所示。有关更多信息,请参阅上面的链接。

     getBlob_withQueryParams(imageUrl: string, params: HttpParams):  Rxjs.Observable<Blob> {
         const headers = new HttpHeaders({
           'Content-Type': 'application/json',
           'Accept': 'application/json'
         });
        return this._http.get<Blob>(imageUrl, {headers: headers, params: params, responseType: 'blob' as 'json' });
      }