如何在函数内部使用DomSanitizer

时间:2017-09-14 14:20:10

标签: angular typescript angular-dom-sanitizer

嗨,我正在建立一个可重用的函数,并清理一些内容,但我不知道如何调用DomSanitizer它总是给我错误和抽象类。 这是我的功能:

export function PostFormat(post){
  let sanitizer: DomSanitizer; // TODO!

  post['title'] = sanitizer.bypassSecurityTrustHtml(post['title']['rendered']);
  post['author'] = post['_embedded']['author'][0];
  post['content'] = sanitizer.bypassSecurityTrustHtml(post['content']['rendered']);
  post['excerpt'] = sanitizer.bypassSecurityTrustHtml(post['excerpt']['rendered']);

  if (post['_embedded']['wp:featuredmedia']){
    if (post['_embedded']['wp:featuredmedia'][0]['media_details']){
      post['featured_image'] = post['_embedded']['wp:featuredmedia'][0]['media_details']['sizes'][this.default_size]['source_url'];
    }
  }
  if (post['_embedded']['replies']){
    post['comments'] = post['_embedded']['replies'][0];
  }
  return post;
}

1 个答案:

答案 0 :(得分:1)

使用它的简便方法是添加导入

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

之后,您可以使用所有消毒剂功能

func trueHTML(post) {
  return this.sanitizer.bypassSecurityTrustHtml(
    post.replace(
      regex,
      match => `<a target="_blank" href="${match}">${match}</a>`
    )
  );
}

并添加inner html

等文字
<div [innerHtml]="post"></div>