如何实例化DomSanitizationService

时间:2019-04-11 05:25:38

标签: angular

我需要从网址中删除不安全的内容: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:无法读取未定义的属性'bypassSecurityTrustHtml'。我在@ angular / platform-b​​rowser中检查了DomSanitizationService,它是一个抽象类,无法实例化。正确的通话方式是什么?我看到了很多这样的答案(How to avoid adding prefix “unsafe” to link by Angular2?),DomSanitizationService是从构造函数传递的,但我不知道在实例化该类时应该传递什么。此外,我不想更改合同构造函数。我想知道什么是实现目标的正确方法。我正在使用angular2。

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

3 个答案:

答案 0 :(得分: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()}}>

答案 1 :(得分:0)

您必须在组件中注入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>

答案 2 :(得分:0)

处理此问题的最佳方法是创建一个消毒管道。稍后,您无需复制功能,而只会添加类似data| sanitize:'html'的内容。

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

管道创建示例here

相关问题