【问题标题】:Angular 4 add URL to innerhtmlAngular 4将URL添加到innerhtml
【发布时间】:2018-03-27 12:03:54
【问题描述】:

我正在使用 angular 4 innerHtml 元素从服务器解析 Html。

  <div *ngFor="let html of htmlToRender">
    <div [innerHtml]="html"></div>
     </div>

我使用 API 从服务器获取 HTML 和响应我使用 JSON.parse() 方法来解析响应类型。 它给了我数组

   this.htmlToRender = JSON.parse(this.htmlToParse._body);

现在的问题是当我渲染 this.htmltoRender 时,我可能会得到一些具有绝对路径的图像或文件 URls。 例如:

<img alt="" src="/Source/ImageBrowser/Image?path=logoCar.qd.png"

从服务器,我会得到这样的路径...我需要添加 URL 以访问该源示例:对于响应,我需要附加示例“http://google.com” IE。,。

<img alt="" src="http://google.com/Analytics/ImageBrowser/Image?path=logo.qd.png">

由于从服务器解析,它们无法追加 那么知道我们如何在 Angular 4 中实现这一点吗?

【问题讨论】:

    标签: json angular ionic2


    【解决方案1】:

    我认为这是由于 angulars 安全机制造成的。尝试使用DomSanitizer 描述的here

    例子:

    updateVideoUrl(id: string) {
       // Appending an ID to a YouTube URL is safe.
       // Always make sure to construct SafeValue objects as
       // close as possible to the input data so
       // that it's easier to check if the value is safe.
       this.dangerousVideoUrl = 'https://www.youtube.com/embed/' + id;
       this.videoUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.dangerousVideoUrl);
    }
    

    【讨论】:

      【解决方案2】:

      您可以在使用正则表达式从服务器获取结果后尝试替换所有 url。查找所有出现的/Source/ImageBrowser/,并将它们替换为您想要的网址。

      var regExp = new RegExp(/\/Source\/ImageBrowser\/*/g);
      this.htmlToRender = this.htmlToRender.replace(regExp,'http://google.com/Analytics/ImageBrowser/');
      

      【讨论】:

      • 如果“/\/Source\/ImageBrowser\/*/g”不是常数怎么办?
      • 如果你有一些你知道的路径,你可以在所有路径上做这个简单的匹配技术。
      【解决方案3】:

      出于性能原因,替换组件本身而不是 html 中的出现,

      由于 this.htmlToRender 中有数组,

      this.htmlToRender.forEach(html => {
         html = html.replace("/Source", "http://google.com/Analytics");
      })
      

      如果你想使用 regExp

      替换
      this.htmlToRender.forEach(html => {
         html = html.replace(/\/Source/i, "http://google.com/Analytics");
      })
      

      如果/Source/ImageBrowser不一样那么你可以这样做,

      this.htmlToRender.forEach(html => {
          let imageUrl = a.split('/');
          imageUrl = imageUrl[imageUrl.length - 1]
          imageUrl = "http://google.com/Analytics/ImageBrowser/" +imageUrl
          html = imageUrl
      })
      

      【讨论】:

      • 如果“来源”不是恒定的怎么办?
      • 更新答案请查收
      • 您好,感谢您的回复。,。目前他们可能正在从服务器端处理......如果我有机会与客户端核实,我将继续努力......
      • 是的,检查一下,如果它不起作用,您可以提出任何疑问。