【问题标题】:how to instantiate DomSanitizationService如何实例化 DomSanitizationService
【发布时间】:2019-04-11 05:25:38
【问题描述】:

我需要从我的 url 中删除 unsafe:unsafe:blob:http://localhost:1234/example,下面是我所做的。

脚本:

import {DomSanitizationService} from '@angular/platform-browser';

class example{
  public DomSanitizer: DomSanitizationService;
  public url;

  constructor() {
    this.url = 'www.example.com';
  }
}

HTML:

<a href={{DomSanitizer.bypassSecurityTrustHtml(url)}}>

但是,它给了我错误:TypeError: Cannot read property 'bypassSecurityTrustHtml' of undefined。我在@angular/platform-b​​rowser 中检查了 DomSanitizationService,它是一个抽象类,无法实例化。什么是正确的调用方式?我看到很多这样的答案(How to avoid adding prefix “unsafe” to link by Angular2?),DomSanitizationService 是从构造函数传递的,但是我不明白什么时候实例化该类,应该传入什么。此外,我不想更改构造函数的合同.我想知道实现我的目标的正确方法是什么。我正在使用 angular2。

更新: 现在我可以通过构造函数注入 DomSanitizationService 来使其工作,但是,在我的测试中, 我需要实例化我的组件,应该为 DomSanitizationService 传入什么?

【问题讨论】:

标签: angular


【解决方案1】:

需要通过构造函数注入DomSanitizer

import {DomSanitizationService} from '@angular/platform-browser';

class example{ 
  public url;

   constructor(private sanitized: DomSanitizer) {

      this.url = 'www.example.com';
   }

   transform() { 
      return this.sanitized.bypassSecurityTrustHtml(this.url);
   }

}

<a href={{transform()}}>

【讨论】:

    【解决方案2】:

    你必须在你的组件中注入DomSanitizer服务

    import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
    
    
    export class Example {
        htmlData:SafeHtml
        constructor(private sanitizer: DomSanitizer) {
           this.url = 'www.example.com';
        }
    
        renderTab() {
           let temp=`<a href="${this.url}">`
                    this.htmlData=this.sanitizer.bypassSecurityTrustHtml(temp);
                }
    
            }
        }
    

    }

    像这样在 html 中使用这个

    <span [innerHTml]="htmlData"></span>
    

    【讨论】:

      【解决方案3】:

      处理它的最佳方法是创建一个消毒剂管道。稍后,您将只添加 data| sanitize:'html' 之类的内容,而不是复制您的功能。

      Angular 文档 -> https://angular.io/api/platform-browser/DomSanitizer

      管道创建示例here.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-02-07
        • 2017-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多