我如何避免添加前缀“不安全”的链接角度2?

使用角度2,有一个设置,以避免添加前缀“ 不安全:”的链接。我需要设置一个协议的链接,它不是默认的白名单在角度2,但它是我们的内部应用程序所需要的,所以结果是一个无效的链接:

    <a href="unsafe:Notes://MYSERVER/C1256D3B004057E8" ..

在旧版的 Angular 中,我们已经编译了 Provider.aHrefSanizationWhitelist,但是在 Angular 2中我找不到类似的东西。

77956 次浏览

Use the DomSanitizer:

import {DomSanitizer} from '@angular/platform-browser';
...
constructor(private sanitizer:DomSanitizer){}
...
let sanitizedUrl = this.sanitizer.bypassSecurityTrustUrl('Notes://MYSERVER/C1256D3B004057E8');

or create a method to return the sanitized url:

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

and then in your template:

<a [href]="sanitize('Notes://MYSERVER/C1256D3B004057E8')" ..

Demo Plunk

Another way is you can create a pipe service to change an unsafe URL to a safe URL, so there isn't any need to rewrite the code in all components. Create a pipe service called safe-url.pipe.ts:

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(url) {
return this.domSanitizer.bypassSecurityTrustResourceUrl(url);
}
}

Then use it in your view.

Example:<a [href]="'Notes://MYSERVER/C1256D3B004057E8' | safeUrl"></a>

NOTE: Don't forget to inject this pipe service in your app.module.ts file:

import { SafeUrlPipe } from './shared/safe-url.pipe'; // Make sure your safe-url.pipe.ts file path is matching.


@NgModule({ declarations: [SafeUrlPipe],...});