用管道绕过消毒(用于代码重复使用)

项目是继从 Angular2 快速入门指南的结构在这里

RootOfProject
|
+-- app
|   |-- app.component.ts
|   |-- main.ts
|   |-- pipeUser.component.ts
|   \-- sanitize.pipe.ts
|
|-- index.html
|-- main.html
|-- pipe.html

main.ts

import { bootstrap } from '@angular/platform-browser-dynamic';
import { AppComponent } from './app.component';

bootstrap(AppComponent);

这将在项目的根目录中找到 index.html 文件,并在此基础上构建。

app.component.ts

import { Component } from '@angular/core';
import { PipeUserComponent } from './pipeUser.component';

@Component({
    selector: 'main-app',
    templateUrl: 'main.html',
    directives: [PipeUserComponent]
})

export class AppComponent { }

这是对使用的其他组件进行分组的顶级组件。

pipeUser.component.ts

import { Component } from '@angular/core';
import { IgnoreSanitize } from "./sanitize.pipe";

@Component({
    selector: 'pipe-example',
    templateUrl: "pipe.html",
    pipes: [IgnoreSanitize]
})

export class PipeUserComponent{
    constructor () { }        
    unsafeValue: string = "unsafe/picUrl?id=";
    docNum: string;

    getUrl(input: string): any {
        if(input !== undefined) {
            return this.unsafeValue.concat(input);
            // returns : "unsafe/picUrl?id=input"
        } else {
            return "fallback/to/something";
        }
    }
}

此组件提供要使用的管道的视图。

sanitize.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizationService } from '@angular/platform-browser';

@Pipe({
    name: 'sanitaryPipe'
})
export class IgnoreSanitize implements PipeTransform {

   constructor(private sanitizer: DomSanitizationService){}

   transform(input: string) : any {
       return this.sanitizer.bypassSecurityTrustUrl(input);
   }

}

这是描述管道格式的逻辑。

index.html

<head>
    Stuff goes here...
</head>
<body>
    <main-app> 
        main.html will load inside here.
    </main-app>
</body>

main.html 中

<othertags> 
</othertags>

<pipe-example>  
    pipe.html will load inside here.
</pipe-example>

<moretags>
</moretags>

pipe.html

<img [src]="getUrl('1234') | sanitaryPipe">
<embed [src]="getUrl() | sanitaryPipe">

如果你在应用程序运行时检查 html,你会发现它看起来像这样:

<head>
    Stuff goes here...
</head>

<body>

    <othertags> 
    </othertags>
    
    <img [src]="getUrl('1234') | sanitaryPipe">
    <embed [src]="getUrl() | sanitaryPipe">
    
    <moretags>
    </moretags>

</body>