Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 向SVG动态添加元素_Angular_Svg - Fatal编程技术网

Angular 向SVG动态添加元素

Angular 向SVG动态添加元素,angular,svg,Angular,Svg,我正在使用由创建的地图的修改版本作为角度(9)模板svg。该文件有12000行长,因此大大降低了编译速度。在枚举所有5248个网格单元(按快捷键e显示在链接地图上)并为每个单元设置id时,我的性能进一步降低。不幸的是,这对于我的用例是必要的 由于这张地图包含12种不同类型的叠加组(即城市、湖泊、路线、海岸线),并且不是一次就需要全部,我想我可以将这个.svg剥离到最小的骨架,一旦用户选择这样做,就通过REST请求不同的元素 下面将向模板中添加正确的行(与从原始svg中裁剪出来的完全相同)。然而,

我正在使用由创建的地图的修改版本作为角度(9)模板svg。该文件有12000行长,因此大大降低了编译速度。在枚举所有5248个网格单元(按快捷键e显示在链接地图上)并为每个单元设置id时,我的性能进一步降低。不幸的是,这对于我的用例是必要的

由于这张地图包含12种不同类型的叠加组(即城市、湖泊、路线、海岸线),并且不是一次就需要全部,我想我可以将这个.svg剥离到最小的骨架,一旦用户选择这样做,就通过REST请求不同的元素

下面将向模板中添加正确的行(与从原始svg中裁剪出来的完全相同)。然而,该组织不会出现。我需要重新启动整个SVG吗?我该怎么做

public async toggleVisibility(elementToDisplay): void {
  try {
    // if elementToDisplay already is part of the .svg, set it visible / invisible here
  } catch(_) {
    this._http.get<string>(`${environment.backend}/worldmap/data/${elementToDisplay}`, { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }).toPromise()
    .then((res: string) => {
       // as an unrelated issue: my spring application is returning a String, yet angular would not resolve this promise
     }.catch((rej: any) => {
       const parser = new DOMParser();
       const doc = parser.parseFromString(rej.error.text, "image/svg+xml");
       this.svgMap.nativeElement.children.namedItem('viewbox').appendChild(doc.lastChild);
     }
  }
公共异步切换可见性(elementToDisplay):无效{
试一试{
//如果elementToDisplay已经是.svg的一部分,请在此处将其设置为可见/不可见
}接住{
这是.\u http.get(`${environment.backend}/worldmap/data/${elementToDisplay}`,{headers:new-HttpHeaders({'Content-Type':'application/json'})}).toPromise()
。然后((res:string)=>{
//作为一个无关的问题:我的spring应用程序返回一个字符串,但angular无法解决这个问题
}.catch((rej:any)=>{
const parser=new DOMParser();
const doc=parser.parseFromString(rej.error.text,“image/svg+xml”);
this.svgMap.nativeElement.children.namedItem('viewbox').appendChild(doc.lastChild);
}
}
调用前的SVG类似于以下内容:

<svg _ngcontent-lys-c61 xmlns:dc="http://purl.org/dc/elements/1.1/" 
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg" 
[...]
id="worldmap"
width="100%" height="100%"
background-color="#000000"
viewBox="145 45 1000 1000">
[...]
  <g _ngcontent-lys-c61 id="viewbox" style="cursor:default;">
    <g _ngcontent-lys-c61 id="ocean"> [...] </g>
    <g _ngcontent-lys-c61 id="lakes"> [...] </g>
    <g _ngcontent-lys-c61 id="landmass">[...] </g>      
     [...]
  </g>
</svg>

[...]
[...] 
[...] 
[...]       
[...]
在通话之后,在landmass组之后还有一个额外的
[…]
(如果我要求生物群落的话)。 我能发现的唯一区别是缺少了_ngContent-lys-c61。然而,事件a changedethetectorref.detectChanges()不会导致显示组。这也不超出其他内容。我在chrome调试器中删除了所有组,生物群落仍然没有显示


另一方面:我发现了很多类似的问题,都是利用D3.js。我不想包括这些问题。

我最终找到了一个解决方案,我将完全删除并编辑这个答案。问题与发送一个无法转换为json的字符串有关——我正在定义一个json头作为标准响应类型

长话短说,我将展示将svg组动态添加到现有svg的整个过程

角度:

// component.ts
@ViewChild('svg') public svgMap: ElementRef<SVGElement>;

// function
const svg = await this._http.get(`pathToServer`, { responseType: 'text' }).toPromise();
const document: Document = new DOMParser().parseFromString(svg, "image/svg+xml");
const group: HTMLCollectionOf<SVGElement> = document.getElementsByTagNameNS('http://www.w3.org/2000/svg', 'g');
const groupToAttach: SVGElement = this.svgMap.nativeElement.children.namedItem('myGroup') as SVGElement;
groupToAttach.appendChild(group.namedItem('paths'))

// component.svg
<svg id="svg">
  <g id="myGroup"></g>
</svg>
//component.ts
@ViewChild('svg')公共svgMap:ElementRef;
//作用
const svg=等待此消息。_http.get(`pathToServer`,{responseType:'text'}).toPromise();
const document:document=new DOMParser().parseFromString(svg,“image/svg+xml”);
常量组:HTMLCollectionOf=document.getElementsByTagnames('http://www.w3.org/2000/svg","g",;
const groupToAttach:SVGElement=this.svgMap.nativeElement.children.namedItem('myGroup')作为SVGElement;
groupToAttach.appendChild(group.namedItem('path'))
//component.svg
弹簧靴:

// imports:
import java.io.InputStreamReader;
import java.io.BufferedReader;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;

// class-level
@Autowired
private ResourceLoader resourceLoader;

//function
@GetMapping(path = "endpoint/{element}")
public ResponseEntity<String> function(@PathVariable String element) throws Exception {
Resource elementResource = resourceLoader.getResource("classpath:/" + element + ".svg");
InputStreamReader is = new InputStreamReader(elementResource.getInputStream(), StandardCharsets.UTF_8);
String data = new BufferedReader(is).lines().collect(Collectors.joining("\n"));

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.valueOf("image/svg+xml"));

return ResponseEntity.ok().headers(headers).contentLength(data.length()).body(data);
//导入:
导入java.io.InputStreamReader;
导入java.io.BufferedReader;
导入org.springframework.http.HttpHeaders;
导入org.springframework.http.ResponseEntity;
导入java.nio.charset.StandardCharset;
导入java.util.stream.collector;
//班级
@自动连线
私有资源加载器;
//作用
@GetMapping(path=“endpoint/{element}”)
公共响应属性函数(@PathVariable字符串元素)引发异常{
ResourceElementResource=resourceLoader.getResource(“类路径:/“+element+”.svg”);
InputStreamReader is=新的InputStreamReader(elementResource.getInputStream(),StandardCharsets.UTF_8);
String data=new BufferedReader(is).lines().collect(collector.joining(“\n”));
HttpHeaders=新的HttpHeaders();
headers.setContentType(MediaType.valueOf(“image/svg+xml”);
返回ResponseEntity.ok().headers(headers).contentLength(data.length()).body(data);
延迟加载svg

<svg xmlns="http://www.w3.org/2000/svg">
  <g id="paths">
    // ...
  </g>
</svg>

// ...