如何导入$ sce - Angular 5

时间:2018-04-12 13:01:52

标签: angular angular5

我想开始使用$sce意味着严格上下文转义,以明确信任HTML。

我曾尝试使用DOMSanitizer对Stirng进行消毒,但似乎无效。

**format-xml.pipe.ts**

import { Pipe, PipeTransform } from '@angular/core';
import * as jQuery from 'jquery';
import { escape } from 'querystring';
import { TestExecutionComponent } from './test-execution/test-execution.component';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Pipe({
  name: 'formatXml'
})
export class FormatXmlPipe implements PipeTransform {
  constructor(private sanitized: DomSanitizer) { }

  testExecutionComponent: TestExecutionComponent;

  transform(xml: String): SafeHtml {
    var formatted = '';
    var reg = /(>)(<)(\/*)/g;
    xml = xml.replace(reg, '$1\r\n$2$3');
    var pad = 0;
    jQuery.each(xml.split('\r\n'), function (index, node) {
      var indent = 0;
      if (node.match(/.+<\/\w[^>]*>$/)) {
        indent = 0;
      } else if (node.match(/^<\/\w/)) {
        if (pad != 0) {
          pad -= 1;
        }
      } else if (node.match(/^<\w[^>]*[^\/]>.*$/)) {
        indent = 1;
      } else {
        indent = 0;
      }

      var padding = '';
      for (var i = 0; i < pad; i++) {
        padding += '  ';
      }

      formatted += padding + node + '\r\n';
      pad += indent;
    });

    var escaped = formatted.replace(/&/g, '&amp;').replace(/</g, '<').replace(/>/g, '&gt;').replace(/ /g, '&nbsp;').replace(/\n/g, '<br />');
    let safeEscaped = this.sanitized.bypassSecurityTrustHtml(escaped);
    console.log(safeEscaped)
    return safeEscaped;
  }
}

但它不起作用。

之后我读到它也可以使用$sce

我想使用正确的字符串(与之前相同的管道)调用管道来使用$sce.trustAsHtml

据我所知,$sce是Angular使用的服务,但似乎我需要先导入它。我怎么能这样做?

我不介意使用Explicitly Trusting$sce

找到一种方法来实现

1 个答案:

答案 0 :(得分:1)

回答angular1:

首先,您需要添加angular sanitize所依赖的$sce

你可以添加,

<script src="http://code.angularjs.org/snapshot/angular-sanitize.js"></script>

然后将其作为依赖项添加到app模块,

<强> angular.module('myApp', ['ngSanitize'])

在控制器中:

您可以通过控制器中的 $sce 导入dependency injection

angular.module('myApp', ['ngSanitize'])
.controller('AppController', ['$scope', '$sce',
  function AppController($scope, $sce) {
     $scope.myFunction(){
      for (var i = 0; i < 5; i++) {
        test[i] = $sce.trustAsHtml(main.links[i]);
      }
     }
  }]);

Here is a plunker example generated from Official docs

回答angular2 +:

正如您所提到的,您应该使用管道<{1}}

  • Angulars DOM清理程序明确将html标记为可信

<强>管:

Dom Sanitizer

<强> HTML:

@Pipe({name: 'safeHtml'})
export class Safe {
  constructor(private sanitizer:DomSanitizer){}

  transform(style) {
    return this.sanitizer.bypassSecurityTrustHtml(style);
  }
}