在Angular中显示带有img标签的SVG

时间:2019-12-30 09:54:45

标签: angular svg

我想从api获取svg并使用image标签显示它。我尝试了以下操作,但不起作用

public svgIcon: any;

public getRequest(url: string) {
  const headers = new HttpHeaders().set('Accept', 'image/svg+xml');
  this.http.get(url,  { headers: headers, responseType: 'blob') }).subscribe({
    const blob = new Blob([svg], {type: 'image/svg+xml'});
    const url = URL.createObjectURL(blob);
    URL.revokeObjectURL(url), {once: true}
    this.svgIcon = url;
  })
}

以及Html中的

<img [src]="this.svgIcon">

2 个答案:

答案 0 :(得分:3)

如下修改您的订阅部分:

public svgIcon: any;

public getRequest(url: string) {
  const headers = new HttpHeaders().set('Accept', 'image/svg+xml');
  this.http.get(url,  { headers: headers, responseType: 'blob') }).subscribe({
    const blob = new Blob([response], {type: 'image/svg+xml'});
    const url = URL.createObjectURL(blob);
    this.svgIcon= this.sanitizer.bypassSecurityTrustUrl(url);
  })
}

以及您的HTML

<img [src]='svgIcon'>

答案 1 :(得分:1)

应该是

<img [src]="svgIcon">

STACKBLITZ DEMO