【问题标题】:Angular 9 - Cant find custom pipe even with shared moduleAngular 9 - 即使使用共享模块也找不到自定义管道
【发布时间】:2020-12-18 05:54:36
【问题描述】:

我想在我的所有组件中使用自定义管道,根据互联网,我应该使用一个共享模块,我在其中导入/导出管道。当我在要使用管道的组件中导入共享模块时,它应该可以工作,但不适用于我。

管道: 从 '@angular/core' 导入 { Pipe, PipeTransform };

@Pipe({
  name: 'empty'
})
export class EmptyPipe implements PipeTransform {

  public transform(value: any, ...args: any[]): string {
    if (!value || value.length < 1) {
      if (args.length < 1) {
        return "-"
      } else {
        return args[0];
      }
    }
    return value;
  }

}

共享模块:

import { CommonModule } from '@angular/common';
import { NgModule} from '@angular/core';
import { EmptyPipe } from './pipes/empty.pipe';

@NgModule({
  imports: [CommonModule],
  declarations: [EmptyPipe],
  exports: [EmptyPipe, CommonModule]
})
export class SharedModule {
}

我如何将它导入到我想使用它的组件中:

import { SharedModule } from '../shared/shared.module';

我如何尝试使用它:

{{companyList.earliest | empty}}

错误:

The pipe 'empty' could not be found

【问题讨论】:

  • 也请分享你的模块,你可能忘记导入或导出管道
  • 也请分享您的模块代码
  • 您是否尝试将其添加为导入:[haredModule.forRoot()]

标签: angular pipe


【解决方案1】:

您不需要将管道导入组件,如果您有多个模块,请将共享模块添加到要使用管道的模块的导入中。然后只需在您的模板中使用它,而无需任何额外的努力。

【讨论】:

    【解决方案2】:

    如果您使用延迟加载路由并且在延迟加载路由中,您将使用该路由而不是在该铺设加载模块文件中声明该路由。 我也遇到过这个问题,所以在那个受人尊敬的模块中声明,问题将得到解决

    【讨论】:

      【解决方案3】:

      我在根目录中提供了自定义管道,它可以在整个应用程序中使用,如下所示。

      @Injectable({
        providedIn: 'root'
      })
      

      不要忘记在共享模块中导出自定义管道。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-01-10
        • 1970-01-01
        • 1970-01-01
        • 2018-11-25
        • 2017-04-16
        • 2019-05-27
        • 2016-09-20
        • 1970-01-01
        相关资源
        最近更新 更多