【问题标题】:Angular custom pipe not be found找不到角度自定义管道
【发布时间】:2017-07-14 08:29:03
【问题描述】:

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

模板解析错误:找不到管道“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;
    }
  }
}

app.module

import { FormatdatePipe } from './shared/pipes/formatdate.pipe';
@NgModule({
  declarations: [
    AppComponent, FormatdatePipe 
  ],

如果我将它导入我的所有模块而不是主体 app.module 中,这个管道可以工作,我是否需要一个常规管道模块或其他东西

【问题讨论】:

  • 你在哪里使用它?
  • 在许多子组件中
  • 你需要导出管道,然后在其他模块中使用该模块
  • 你有例子吗?

标签: angular angular2-custom-pipes


【解决方案1】:

管道(如组件和指令)不像服务那样​​在全局范围内工作。

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

这样定义:

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

@NgModule({
  declarations: [
    FormatdatePipe 
  ],
  exports: [
    FormatdatePipe
  ]
})   
export class SomeUtilModule {}

然后将此模块导入您要使用的地方,它应该可以工作:)

【讨论】:

  • 谢谢,但是否可以只在 appmodule 中导入我的新管道模块,如下所示:export class SomeUtilModule { static forRoot() { return { ngModule: SomeUtilModule, providers: [], }; } }
  • 不,我不这么认为,afaik。这个想法是模块中的所有内容都定义了他们需要的东西,因此它们可以在其他任何地方轻松重用,而不会产生歧义。唯一的例外是具有非平凡依赖注入机制的服务。
  • 这真的是SharedModule,它包含指令和管道的导出和声明。
  • 如果它已经插入到模块中(例如,SharedModule),请注意它必须列在exports 数组中才能在外部使用。 =](那是我的错误,ng g pipe 没有将其插入其中,仅在declarations 处插入)。