簡體   English   中英

沒有CustomPipe的提供者 - 角4

[英]No Provider for CustomPipe - angular 4

我有一個使用角度十進制管道的自定義十進制格式管道。 此管道是共享模塊的一部分。 我在功能模塊中使用它,並在運行應用程序時沒有提供程序錯誤。

如果有任何拼寫錯誤,請忽略

./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

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

...

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

我在其中一個組件中注入自定義管道並調用transform方法來獲取轉換后的值。 共享模塊導入到功能模塊中。

如果要在組件中使用pipe的transform()方法,還需要將CustomPipe添加到模塊的提供者:

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

...

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

除了將CustomPipe添加到模塊的提供者列表之外,另一種方法是添加到組件的提供者。 如果您的自定義管道僅在少數組件中使用,這將非常有用。

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

希望這可以幫助。

您還可以使管道可注入(與使用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