Angular:如何从后端加载svg文件并将其内容用作模板?

问题描述

我需要一种从Spring Boot后端加载SVG日期并将其内容用作Angular模板的方法

我的请求当前如下所示:

   getSVG (): Observable <any> {
     return this.http.get(`${environment.apiUrl}/path/to/svg/svg.svg`,{headers: new HttpHeaders ({'Content-Type': 'image/svg+xml'})});
   }

在我的组件中,它的命名如下:

   ngOnInit () {
     this.myService.getSVG().subscribe((data) => {
       console.log('data',data);
     });
   }

请求通过,因此我可以在“网络”标签获取svg文件。但是在浏览器控制台中,我收到以下错误消息:

backend returned code 200,body was: [object Object]           main.js:1388:25
    intercept http://localhost:8425/main.js:1388
    error http://localhost:8425/vendor.js:223317
    onLoad http://localhost:8425/vendor.js:41005
    invokeTask http://localhost:8425/polyfills.js:663
    onInvokeTask http://localhost:8425/vendor.js:76954
    invokeTask http://localhost:8425/polyfills.js:662
    runTask http://localhost:8425/polyfills.js:431
    invokeTask http://localhost:8425/polyfills.js:744
    invokeTask http://localhost:8425/polyfills.js:1885
    globalZoneAwareCallback http://localhost:8425/polyfills.js:1922


ERROR OK                                                       vendor.js:47101:33
    defaultErrorLogger http://localhost:8425/vendor.js:47101
    handleError http://localhost:8425/vendor.js:47153
    next http://localhost:8425/vendor.js:77725
    schedulerFn http://localhost:8425/vendor.js:73301
    __tryOrUnsub http://localhost:8425/vendor.js:219977
    next http://localhost:8425/vendor.js:219916
    _next http://localhost:8425/vendor.js:219866
    next http://localhost:8425/vendor.js:219843
    next http://localhost:8425/vendor.js:219629
    emit http://localhost:8425/vendor.js:73263
    onHandleError http://localhost:8425/vendor.js:77012
    invoke http://localhost:8425/polyfills.js:628
    run http://localhost:8425/polyfills.js:387
    runOutsideAngular http://localhost:8425/vendor.js:76893
    onHandleError http://localhost:8425/vendor.js:77009
    handleError http://localhost:8425/polyfills.js:632
    runTask http://localhost:8425/polyfills.js:434
    invokeTask http://localhost:8425/polyfills.js:744
    invoke http://localhost:8425/polyfills.js:733
    timer http://localhost:8425/polyfills.js:2816

我想提取SVG的内容并在模板中使用它,例如:

my.component.svg

<svg width="400" height="110">
  <rect width="300" height="100" style="fill:rgb(0,255);stroke-width:3;stroke:rgb(0,0)" />
    ...
</svg>

解决方法

首先,您应该测试是否可以从服务器获取svg文件。 您可以通过将网址粘贴到浏览器中进行测试(例如) 如果您要获取文件的端点是 http:// localhost:3000 / path / to / svg / svg.svg 通过将其粘贴到浏览器中,您应该会看到图像

如果一切正常,请尝试

检查是否在appModule中导入HttpClientModule

检查是否从'@ angular / common / http'注入了httpClient服务导入

从获取请求中删除标题

对于显示svg,您可以轻松地将url绑定到html图像标签src中,并且不需要编写方法来从服务器获取它

<img [src]="svgUrl" />

或者您可以使用角形@viewchild decorator来引用元素,然后将svg直接注入模板中