You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中XSLT转换绑定[innerHTML]报错及HttpClient调用异常排查

问题解决方案

1. 修复XSLT转换结果绑定[innerHTML]显示[object DocumentFragment]的问题

XSLTProcessor.transformToFragment()返回的是DocumentFragment对象,而Angular的[innerHTML]指令需要的是HTML字符串,直接绑定对象会被转为[object DocumentFragment]字符串显示。解决方法是将DocumentFragment转为HTML字符串,并通过DomSanitizer处理为安全HTML:

修改convert()函数:

convert() {
  const xml = this.loadXMLDoc("assets/xml/test.xml");
  const xsl = this.loadXMLDoc("assets/xml/test.xsl");
  const xsltProcessor = new XSLTProcessor();
  xsltProcessor.importStylesheet(xsl);
  const resultDocument = xsltProcessor.transformToFragment(xml, document);

  // 将DocumentFragment转换为HTML字符串
  const tempContainer = document.createElement('div');
  tempContainer.appendChild(resultDocument);
  const htmlContent = tempContainer.innerHTML;

  // 标记HTML为安全内容,避免Angular安全拦截
  this.xmlcontent = this.sanitizer.bypassSecurityTrustHtml(htmlContent);
}

这样修改后,重复点击转换按钮时,xmlcontent会被新的HTML内容覆盖,不会出现重复添加的问题。

2. 修复getHtmlFile()中的TypeError: Cannot read properties of undefined (reading 'get')异常

这个错误的原因是依赖注入未正确完成:

  • 类中声明的_httpClient和sanitizer变量,没有通过Angular的依赖注入机制赋值,导致变量为undefined。
  • 构造函数中仅声明了参数,但没有用private/public修饰符,Angular不会自动将注入实例绑定到类属性。

修改组件类的构造函数和属性声明:

import { HttpClient } from '@angular/common/http';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { OnInit } from '@angular/core';

export class XmlconvertComponent implements OnInit {
  // 明确类型为SafeHtml,避免any类型
  xmlcontent: SafeHtml | undefined;
  htmlcontent: SafeHtml | undefined;

  // 用private修饰注入参数,Angular自动绑定到类属性
  constructor(private _httpClient: HttpClient, private sanitizer: DomSanitizer) { }

  ngOnInit(): void { }

  loadXMLDoc(filename: string): Document | null {
    const xhttp = new XMLHttpRequest();
    xhttp.open("GET", filename, false);
    try { xhttp.responseType = 'document' } catch (err) { } // 兼容IE11
    xhttp.send("");
    return xhttp.responseXML;
  }

  getHtmlFile() {
    let path = 'assets/xml/test.html';
    this._httpClient.get(path, {responseType: "text"}).subscribe(
      data => {
        this.htmlcontent = this.sanitizer.bypassSecurityTrustHtml(data);
      });
  }
}

关键修改点:

  • 在构造函数参数中添加private修饰符,让Angular自动将HttpClient和DomSanitizer实例赋值给类属性。
  • 为xmlcontent和htmlcontent指定SafeHtml类型,符合Angular安全规范。

内容的提问来源于stack exchange,提问作者Reegan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 02:45:01