如何在函数内部使用 DomSanitizer

How to use DomSanitizer inside a function

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

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;
}

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

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

之后就可以使用sanitizer的所有功能了

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

并添加您的文字 inner html

<div [innerHtml]="post"></div>