【问题标题】:angular 2 bypassSecurity [duplicate]angular 2 bypassSecurity [重复]
【发布时间】:2017-06-11 19:48:57
【问题描述】:

我有一个包含数据的 JSON 文件。在每个对象中,我都有一个带有 HTML 标记、样式和文本的“描述”字段,如下所示:

<div>__localname__</div>
 <div style="color: #555; margin-top:2px; margin-left:10px;"><div style="display:inline; color:#d34319 ">[DV]</div> Проверка домена (выдача от 5 минут)</div>
 <div style="color: #555; margin-top:2px; margin-left:10px;">Защищает домен с www и без www (указывайте при заказе домен с www, например www.domain.ru)</div>
 <div style="color: #555; margin-top:2px; margin-left:10px;">Гарантия 10000$</div>

我想在悬停时显示这些样式数据 问题是 Title ([attr.title] or Title, or [title]) 没有显示 div 的样式,浏览器建议我访问这个链接http://g.co/ng/security#xss

我将 Pipe 与 DomSanitizer 一起使用:

@Pipe({ name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform  {
  constructor(private sanitized: DomSanitizer) {}
  transform(value: any) {
    return this.sanitized.bypassSecurityTrustHtml(value);
  }
}

这就是我获取数据的方式:

1) 我得到 JSON

getPriceList() {
    return this.httpGet('./ssl.json');
  }

2) 使其在网页上可见

ngOnInit() {
    this.appService.getPriceList().subscribe(data => {
      this.pricelist = data.pricelist;
    });
  }

3) Html,我想在悬停时显示样式“标题”

<tbody>
      <tr *ngFor="let item of pricelist">
        <td>
          <a data-toggle="tooltip" data-html="true" 
          title="{{item.description|safeHtml}}">
              {{ item.name }}
          </a>
        </td>
        <td> от {{ item.price.period[0].cost }} {{ item.price.currency }}</td>
        <td> <div [innerHTML]='item.description | safeHtml'></div> </td>
      </tr>
    </tbody>

[innerHTML] 工作正常,但标题不... 如何使用 JSON 文件中的数据?

这是错误的屏幕截图: https://yadi.sk/i/uieFFCfa3BMq4v

【问题讨论】:

  • 您是否在网络服务器中运行您的应用程序?还是您使用简单的基于文件的方法?看看this
  • @Ken 没关系,它是一个angular2 sanitizer,他必须使用DomSanitizer 类的方法bypassSecurityTrustHtml

标签: javascript json angular


【解决方案1】:

将此Pipe 添加到您的组件中。

import { DomSanitizer } from '@angular/platform-browser';
@Pipe({ name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform  {
  constructor(private sanitized: DomSanitizer) {}
  transform(value) {

    return this.sanitized.bypassSecurityTrustHtml(value);
  }
}

然后您可以在循环中的元素上使用Pipe。 例如:

<div *ngFor="let price of pricelist">
    {{ price.description | safeHtml }}
</div>

【讨论】:

  • 它适用于表格,所有带有标签的数据都显示正确!谢谢!但由于某些原因,它不适用于带有引导工具提示的标签“标题”:` {{ item.name }} `它显示像这样带有标签yadi.sk/i/uieFFCfa3BMq4v
  • @GeorgeMadiarov 请尝试使用[attr.title] 或不带括号的标题title="{{item.description|safeHtml}}"
  • 同样的问题:[attr.title]="item.description|safeHtml" title="{{item.description|safeHtml}}" 和许多不同的修改:重写主帖
猜你喜欢
  • 2018-09-30
  • 2017-09-06
  • 1970-01-01
  • 2016-07-14
  • 2018-02-01
  • 2017-04-04
  • 2016-06-28
  • 1970-01-01
  • 2017-08-25
相关资源
最近更新 更多