用管道繞過消毒(用於程式碼重複使用)
專案是繼從 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>