首页 > 解决方案 > 错误类型错误:在 innerhtml 中解析脚本时无法读取未定义的属性“文档”

问题描述

我正在以角度解析内部 HTML 中的脚本,我在此链接中提到

我的代码是

import { Component, OnInit, Input,OnChanges, ViewChild, ViewEncapsulation, SimpleChange, SimpleChanges } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'lib-html-viz',
  templateUrl: './html-viz.component.html',
  styleUrls: ['./html-viz.component.css'],

})
export class HtmlVizComponent implements OnInit ,OnChanges{

  constructor(public sanitzer:DomSanitizer) { }
  @Input() data;
  @Input() reportOptions
  innerHtml
  @ViewChild('htmlContainer') container;

  ngOnInit() {
  }
  ngOnChanges(changes:SimpleChanges)
  { if(changes.reportOptions)
    {
      this.setInnerHtml()
    }
  }
  setInnerHtml()
  {
     if(this.reportOptions.htmlRes)
     { let final=this.reportOptions.htmlRes
       this.innerHtml=this.sanitzer.bypassSecurityTrustHtml(final)
       setTimeout(()=>{
        let scripts = this.container.nativeElement.getElementsByTagName('script');
        for (let script of scripts){
          eval(script.text)
        }
       })

     }
  }

}

用法<div #htmlContainer *ngIf="innerHtml" [innerHTML]="innerHtml"></div>

在这段代码中,我从 API 获得 HTML 响应,我正在解析脚本标签并显示 HTML 输出。这样做时,我收到这样的错误

errors.ts:35 ERROR TypeError: Cannot read property 'document' of undefined
    at eval (eval at <anonymous> (html-viz.component.ts:34), <anonymous>:3:3636)
    at eval (eval at <anonymous> (html-viz.component.ts:34), <anonymous>:5:22947)
    at html-viz.component.ts:34
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
    at Object.onInvokeTask (ng_zone.ts:262)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:420)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:188)
    at push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask (zone.js:496)
    at ZoneTask.invoke (zone.js:485)
    at timer (zone.js:2054)

我不知道代码在哪里中断

我已经在一个文件中添加了我的 HTML 响应,这是这里的链接

有人可以帮我解决这个问题,还是有其他方法可以解析 HTML 的角度

提前致谢:)

标签: angularinnerhtml

解决方案


推荐阅读