找不到角度自定义管道

Ale*_*dro 4 angular2-custom-pipes angular

在我的应用程序中,我需要一个全局自定义管道,我尝试按照角度管道实现它, 但我总是看到这个错误

模板解析错误:找不到管道'formatdate'

formatdate.pipe

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'formatdate'
})

export class FormatdatePipe implements PipeTransform {

  transform(dateJson: any, args?: any): any {
.
 //code...
.
      return dateJson;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

app.module

import { FormatdatePipe } from './shared/pipes/formatdate.pipe';
@NgModule({
  declarations: [
    AppComponent, FormatdatePipe 
  ],
Run Code Online (Sandbox Code Playgroud)

如果我在我的所有模块中导入它而不是在主app.module中导入此管道,我是否需要例程管道模块或其他东西

edd*_*P23 14

管道(如组件和指令)不像服务那样​​全局工作.

您需要在某个模块中定义管道.然后,您可以在该模块中定义的组件中使用它.另一种方法是将管道添加到模块的导出,然后将该模块导入要使用它的模块中.

像这样定义:

import { FormatdatePipe } from './shared/pipes/formatdate.pipe';

@NgModule({
  declarations: [
    FormatdatePipe 
  ],
  exports: [
    FormatdatePipe
  ]
})   
export class SomeUtilModule {}
Run Code Online (Sandbox Code Playgroud)

然后导入这个模块你想要使用它,它应该工作:)

  • 这实际上是包含指令和管道的导出和声明的“SharedModule”。 (2认同)