#angular #typescript #svg #angular-directive #angular-template
#angular #typescript #svg #angular-директива #angular-template
Вопрос:
Мне нужен способ загрузить SVG-дату из серверной части Spring Boot и использовать ее содержимое в качестве шаблона 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,0,255);stroke-width:3;stroke:rgb(0,0,0)" />
...
</svg>
Ответ №1:
Вы не можете определить компонент в браузере после получения шаблона из сети. Компонент angular компилируется вместе с шаблоном, который должен существовать во время компиляции. Если вы действительно хотите вставить динамическое svg-содержимое, вы можете использовать ‘innerHTML’ после получения svg-файла из http-запроса. См . https://www.chrisjmendez.com/2017/06/17/angular-dynamically-inserting-svg-into-an-element /