Angularv4.初体验


1208 浏览 5 years, 2 months

10 管道 Pipes & Custom Pipes

版权声明: 转载请注明出处 http://www.codingsoho.com/

10 -- Pipes & Custom Pipes

前面我们通过函数对网站进行了转换,改函数适用了当前component,如果我们想在所有的app里使用这个函数呢?可以用pipe,这个跟django的filter非常像。

先学习一个预定义的pipe (date)

可以在video-list.component.ts定义一个变量todayDate

  ngOnInit() {
    this.todayDate = new Date()
  }

然后在video-list.component.html里显示它

{{todayDate | date: "MM/dd/yy"}}

也有其他的参数,比如short

参考 https://angular.io/guide/pipes

接下来我们实现自己的pipe

在app下面创建目录utility

在根目录下面(app上一级目录)运行命令

ng g pipe safe

它在app下面创建两个文件

safe.pipe.spec.ts
safe.pipe.ts

同时在app.module.ts下面添加了这个pipe

import { SafePipe } from './safe.pipe';

@NgModule({
  declarations: [
    AppComponent,
    VideoListComponent,
    VideoDetailComponent,
    SafePipe
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})

我们希望的是这个文件在utility目录下面,所以把它们移过去

接下来将getEmbedUrl的相关功能移到safe.pipe.ts里

import { DomSanitizer } from '@angular/platform-browser'

@Pipe({
  name: 'safe'
})
export class SafePipe implements PipeTransform {

  constructor(private sanitizer: DomSanitizer) { }

  transform(value: any, args?: any): any {
    if(value){
      return this.sanitizer.bypassSecurityTrustResourceUrl(value)
    }
  }
}

这样getEmbedUrl可以直接返回未处理链接地址

  getEmbedUrl(item){
    return '[http://player.youku.com/embed/](http://player.youku.com/embed/)' + item.embed + '=='
  }

同时在video-list.component.html添加pip

<iframe [src]='getEmbedUrl(item)|safe' width='480' height='400' frameborder=0 allowFullScreen='true'></iframe>