Angular2 DomSanitizer问题

时间:2017-02-02 21:12:10

标签: angular typescript inline-styles angular-dom-sanitizer

我正在尝试使用 background-image 内联我的 * ngFor 列表项。 我是我的组件类我声明了一个变量,它存储了我的图片网址的一个公共部分(例如,它的 http://storage.com/ )以及图像的URL的唯一部分 this.image (比如,他们是 QWERTY / 01.JPG, uiop / 02.JPG, asdfg / 03.jpg , 等)

一起看起来像

export class AppComponent {
cartItems: any;
image: any;

constructor(public cartService: CartService, private sanitizer: DomSanitizer) { }

ngOnInit(){
let sanitizedUrl = this.sanitizer.bypassSecurityTrustUrl('http://storage.com/' + this.image);

  this.cartService.getCartItems().subscribe(
     (data) => this.cartItems = data
  );

}

在视图中我有 cartItem 是生成 * ngFor 列表的项目:

<span class="col cart__item--imageBox" 
[style.background-image.url]="('sanitizedUrl' + cartItem.image)">
</span>

控制台显示警告:

WARNING: sanitizing unsafe style value sanitizedUrl<<here go the images URLs endings - qwerty/01.jpg, uiop/02.jpg, asdfg/03.jpg, etc >> (see http://g.co/ng/security#xss).

我认为网址是&#34;已消毒&#34;。

如上面的示例所示,如何能够使用 background-image 样式内联?

UPD! 我将我的NgOnInit函数重写为:

ngOnInit(){
let addSanitizedUrl = (cartItem) => {
      cartItem.sanitizedImageUrl = this.sanitizer.bypassSecurityTrustStyle('https://s27.postimg.org/' + this.image + cartItem.image)
      return cartItem;
    };

this.cartService.getCartItems().subscribe(
    (data) => this.cartItems = data.map(addSanitizedUrl) ngOnInit(){
let addSanitizedUrl = (cartItem) => {
      cartItem.sanitizedImageUrl = this.sanitizer.bypassSecurityTrustStyle('https://s27.postimg.org/' + this.image + cartItem.image)
      return cartItem;
    };

  this.cartService.getCartItems().subscribe(
      (data) => this.cartItems = data.map(addSanitizedUrl)
  );

}

警告消失了,但似乎应用程序没有找到我在服务中传递的任何图像。只是无法通过DevTools Inspector找到它们。

1 个答案:

答案 0 :(得分:0)

只对您网址的一部分进行了清理。要完全清理

将组件添加到组件中以进行清理

sanitize(url:string){
    return this.sanitizer.bypassSecurityTrustUrl(url);
  }

并且HTML将在URL传递之前调用上述方法,如下所示

<span class="col cart__item--imageBox" 
[style.background-image.url]="sanitize('sanitizedUrl' + cartItem.image)">
</span>

此外它只是一个警告,可以忽略。