简体   繁体   English

没有CustomPipe的提供者 - 角4

[英]No Provider for CustomPipe - angular 4

I've a custom decimal format pipe that uses angular Decimal pipe inturn. 我有一个使用角度十进制管道的自定义十进制格式管道。 This pipe is a part of the shared module. 此管道是共享模块的一部分。 I'm use this in feature module and getting no provider error when running the application. 我在功能模块中使用它,并在运行应用程序时没有提供程序错误。

Please ignore if there are any typo . 如果有任何拼写错误,请忽略

./src/pipes/custom.pipe.ts ./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) {
    ...
}

./modules/shared.module.ts ./modules/shared.module.ts

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

...

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

I inject the custom pipe in one of the components and call transform method to get the transformed values. 我在其中一个组件中注入自定义管道并调用transform方法来获取转换后的值。 The shared module is imported in he feature module. 共享模块导入到功能模块中。

If you want to use pipe's transform() method in component, you also need to add CustomPipe to module's providers: 如果要在组件中使用pipe的transform()方法,还需要将CustomPipe添加到模块的提供者:

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

...

@NgModule({
  imports:      [ .. ],
  declarations: [ CustomPipe ],
  exports:    [ CustomPipe ],
  providers:    [ CustomPipe ]
})
export class SharedModule { }

Apart from adding the CustomPipe to the module's provider list, an alternative is to add to the component's providers. 除了将CustomPipe添加到模块的提供者列表之外,另一种方法是添加到组件的提供者。 This can be helpful if your custom pipe is used in only a few components. 如果您的自定义管道仅在少数组件中使用,这将非常有用。

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

Hope this helps. 希望这可以帮助。

You could also make the pipe Injectable (the same way it is done with the services you create using the cli): 您还可以使管道可注入(与使用cli创建的服务完成相同):

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

    @Pipe({
      name: 'customDecimalPipe'
    })
    @Injectable({
      providedIn: 'root'
    })
    export class CustomPipe extends PipeTransform {
      ...
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM