gpt4 book ai didi

angular - Angular 的 SafeUrl 是什么

转载 作者:太空狗 更新时间:2023-10-29 18:19:44 26 4
gpt4 key购买 nike

documentation只说:

Marker interface for a value that's safe to use as a URL linking to a document.

什么时候应该使用 SafeUrl

最佳答案

您使用 SafeUrlDomSanitizer 来告诉 Dom 您的应用信任某个 URL。

Angular treats all values as untrusted by default. When a value is inserted into the DOM from a template, via property, attribute, style, class binding, or interpolation, Angular sanitizes and escapes untrusted values.

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

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

unsafe value used in a resource URL context

为避免这种情况,您可以使用 SafeUrlDomSanitizer 来告诉您的应用您正在使用的动态 URL 是可信的:

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

查看此 working demo .

关于angular - Angular 的 SafeUrl 是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46302873/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com