角在href中的url之前添加不安全-清理不安全的URL [英] angular add unsafe before url in href - sanitizing unsafe URL
问题描述
我正在尝试打开一个应用程序.当我提供静态网址时,它的工作正常.但是,当我在* ngFor中创建动态href标签时,我可以看到在URL之前添加了不安全的关键字,并且该关键字不起作用.
I am trying to open an app. Its working fine when I give a static URL. But as I create a dynamic href tag in *ngFor I can see unsafe keyword is added before the URL and it's not working.
我正在Angular 6上运行,并在服务中获取ID.在ngFor中,我循环结果并创建带有ID的链接以打开应用程序.我创建了一个管道,但仍然无法正常工作.
I am running on Angular 6. And getting the Id in a service. In ngFor I am looping the result and creating a link with Id to open the app. I create a pipe but it's still not working.
安全管道
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({
name: 'safeurl'
})
export class SafeurlPipe implements PipeTransform {
constructor(private domSanitizer: DomSanitizer) {}
transform(value: any) {
return this.domSanitizer.bypassSecurityTrustUrl(value);
}
}
在组件中,我在ngFor标签之间添加了以下行
In the component I added the below line between ngFor tag
<a href="appName://joinTournament?id={{t.tag}} |safeurl">Join</a>
推荐答案
您需要在插值内使用管道.用你的方式,它只是一个字符串(href的一部分).这意味着,角度不会将其识别为管道或应用程序的一部分.同样,您只需要绑定值本身,而不必绑定其他任何东西.您可以将appName://joinTournament?id=
作为参数传递给管道.
You need to use your pipe within interpolation. With your way it's just a string (part of href). It means, angular does not recognize it as a pipe or part of your application. Also, you need to bind the value itself only and nothing else. In your case you can pass appName://joinTournament?id=
as a parameter to the pipe.
这是一个工作解决方案.
如下所示向管道添加另一个参数
Add another parameter to your pipe as follows
transform(value: any, prefix = '') {
return this.domSanitizer.bypassSecurityTrustUrl(prefix + value);
}
然后更改
<a href="appName://joinTournament?id={{t.tag}} |safeurl">Join</a>
到
<a [href]="t.tag | safeurl: 'appName://joinTournament?id='">Join</a>
这篇关于角在href中的url之前添加不安全-清理不安全的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!