本文介绍了什么是Angular的SafeUrl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档仅表示:

我什么时候应该使用SafeUrl?

推荐答案

您可以将SafeUrlDomSanitizer一起使用,以告知Dom应用程序信任URL.

You use SafeUrl along with DomSanitizer to tell the Dom that a URL is trusted by your app.

例如,执行以下操作将导致错误:

For example, doing the following will result in an error:

<iframe [src]="iframeSrc"></iframe>

在您的ts中:

export class AppComponent  {
  iframeSrc: string;
  constructor(){
      let id = 's7L2PVdrb_8'; // Game of Thrones Intro Video
      this.iframeSrc = `https://www.youtube.com/embed/${id}`;
  }
}

为避免这种情况,请将SafeUrlDomSanitizer结合使用,以告诉应用程序所使用的动态URL受信任:

To avoid this, you use SafeUrl with DomSanitizer to tell you app that the dynamic URL you are using is trusted:

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

export class AppComponent  {
    iframeSrc: SafeUrl;
    constructor(private sanitizer: DomSanitizer){
        let id = 's7L2PVdrb_8'; // Game of Thrones Intro Video
        let url = `https://www.youtube.com/embed/${id}`;
        this.iframeSrc = this.sanitizer.bypassSecurityTrustResourceUrl(url);
}

请参见工作演示.

这篇关于什么是Angular的SafeUrl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 18:03