当angular 引用外部的url 有时候会报错,比如在iframe 中嵌入了外部url

通用一点的做法是新建一个pipe 用来让url 变为安全 。

代码如下

Safe.pipe.ts

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

@Pipe({
  name: 'safe'
})

export class SafePipe implements PipeTransform {

  constructor(private sanitizer: DomSanitizer) { }
  transform(url) {
    return this.sanitizer.bypassSecurityTrustResourceUrl(url);
  }

}

module中引入

import { SafePipePipe } from ‘./SafePipe.pipe’;

@NgModule({
   imports: [
    
   ],
   declarations: [
      ...
      SafePipePipe
   ],
   entryComponents: [
    
   ],
   exports: [
     
   ]
})

HTML 中使用

 <iframe [src]=”url | safe”></iframe>

发表评论