2017-07-14 19 views
1

在我的應用程序需要在全球範圍的自定義管道,我嘗試實現它下面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這條管道的作品,我需要一個routin管模塊或東西

+0

你在哪裏使用它? – Sajeetharan

+0

在許多子組件中 – Alessandro

+0

您需要導出管道然後在其他模塊中使用該模塊 – Sajeetharan

回答

5

管道(如組件和指令)不像服務那樣​​在全球範圍內工作。

您需要在某個模塊中定義管道。然後,您可以在該模塊中定義的組件中使用它。另一種方法是將管道添加到模塊的導出中,然後將該模塊導入要使用它的模塊中。

將其定義是這樣的:

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

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

然後導入這個模塊要使用它,它應該工作:)

+0

謝謝,但是否可以導入我的新pipemodule只用的AppModule是這樣的:'出口類SomeUtilModule { 靜態forRoot(){ 回報{ ngModule:SomeUtilModule, 提供商:[], }; } }' – Alessandro

+0

不,我不認爲它是,afaik。這個想法是,模塊中的所有內容都定義了他們需要的內容,因此它們可以在其他任何地方輕鬆地重用,而不會出現歧義。唯一的例外是具有非平凡依賴注入機制的服務。 – eddyP23

+0

這實際上是'SharedModule',它包含指令和管道的輸出和聲明。 – Chrillewoodz