Angular自定义管道未找到。

11
在我的应用程序中,我需要一个全局的自定义管道。我尝试按照 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中导入时才起作用,我需要一个常规的管道模块或类似的东西吗?

你在哪里使用它? - Sajeetharan
在许多子组件中 - Alessandro Celeghin
你需要导出管道,并在其他模块中使用该模块。 - Sajeetharan
你有一些例子吗? - Alessandro Celeghin
1个回答

23

管道(和组件、指令一样)不像服务那样在全局范围内起作用。

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

像这样定义:

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

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

然后在你想使用它的地方导入这个模块,它应该可以正常工作 :)


谢谢,但是是否可以像这样仅在appmodule中导入我的新pipemodule:`export class SomeUtilModule { static forRoot() { return { ngModule: SomeUtilModule, providers: [], }; } }` - Alessandro Celeghin
不,我认为它不是这样的,据我所知。这个想法是模块里定义了它们需要的一切,这样它们就可以在任何地方被重复使用而不会产生歧义。唯一的例外是具有非平凡依赖注入机制的服务。 - eddyP23
2
这实际上是 SharedModule,其中包含指令和管道的导出和声明。 - Chrillewoodz
如果它已经被插入到一个模块中(例如像“SharedModule”),请注意它必须在“exports”数组中列出以便在外部使用。=](那是我的错误,“ng g pipe”没有将它插入那里,只在“declarations”中)。 - giovannipds
当开始使用新的自定义管道时,我遇到了一个错误:“无法读取未定义的属性(读取'ondestroy')”。关键是按照这里所示的方式导出它,然后在需要的模块中进行导入。大多数管道的文档/示例都提到了声明它。但是对于多个模块来说,仅仅声明是不够的 - 导出也是必需的。 - Paul Evans

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接