没有CustomPipe的提供者 - 角4

mpe*_*rle 29 angular-module angular-pipe angular

我有一个使用角度十进制管道的自定义十进制格式管道.此管道是共享模块的一部分.我在功能模块中使用它,并在运行应用程序时没有提供程序错误.

如果有任何拼写错误,请忽略.

./src/pipes/custom.pipe.ts

import { DecimalPipe } from '@angular/common';
..
@Pipe({
    name: 'customDecimalPipe'
})
...
export class CustomPipe {
constructor(public decimalPipe: DecimalPipe) {}
transform(value: any, format: any) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

./modules/shared.module.ts

import  { CustomPipe } from '../pipes/custom.pipe';

...

@NgModule({
  imports:      [ .. ],
  declarations: [ CustomPipe ],
  exports:    [ CustomPipe ]
})
export class SharedModule { }
Run Code Online (Sandbox Code Playgroud)

我在其中一个组件中注入自定义管道并调用transform方法来获取转换后的值.共享模块导入到功能模块中.

Ste*_*ota 63

如果要transform()在组件中使用管道方法,还需要添加CustomPipe到模块的提供程序:

import  { CustomPipe } from '../pipes/custom.pipe';

...

@NgModule({
  imports:      [ .. ],
  declarations: [ CustomPipe ],
  exports:    [ CustomPipe ],
  providers:    [ CustomPipe ]
})
export class SharedModule { }
Run Code Online (Sandbox Code Playgroud)

  • 谢谢您的回答。所以这意味着管道成为可注射的,因此必须提供它。我对吗。? (2认同)

Jos*_*igo 14

您还可以使管道可注入(与使用 cli 创建的服务相同):

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

    @Pipe({
      name: 'customDecimalPipe'
    })
    @Injectable({
      providedIn: 'root'
    })
    export class CustomPipe extends PipeTransform {
      ...
    }
Run Code Online (Sandbox Code Playgroud)


Far*_*ruq 7

除了将添加CustomPipe到模块的提供程序列表之外,另一种方法是添加到组件的提供程序。如果仅在少数几个组件中使用了自定义管道,这将很有帮助。

import  { CustomPipe } from '../pipes/custom.pipe';
...
@Component({
    templateUrl: './some.component.html',
    ...
    providers: [CustomPipe]
})
export class SomeComponent{
    ...
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。

  • 这比公认的答案更有意义(不敢相信赞成票少了 10 倍)!为特定组件设计的管道**不应该在全球范围内可用**。欣赏法鲁克的逻辑。 (3认同)