Angular 2中的全局管道 [英] Global pipe in Angular 2
问题描述
我想在所有应用程序中使用管道.根据我在Angular文档和Internet中阅读的内容,如果我在根模块声明中声明一个管道,则该管道将在所有应用程序中可用.我有这个AppModule代码:
I want to make a pipe available in all the app. Acording with what I read in the Angular docs and internet, if I declare a pipe into the root module declaratios, it make's the pipe available in all the application. I have this AppModule code:
@NgModule({
imports: [ BrowserModule, NavbarModule],
declarations: [ AppComponent, TranslatePipe],
bootstrap: [ AppComponent],
})
export class AppModule { }
这对于子模块:
@NgModule({
imports: [ CommonModule],
declarations: [ NavbarMenuComponent],//<---Call the pipe in this component
})
export class NavbarModule { }
管道:
@Pipe({
name: 'translate',
pure: false
})
export class TranslatePipe implements PipeTransform {
constructor() { }
transform(value: string, args: any[]): any {
return value + " translated";
}
}
但是当我在NavbarMenuComponent模板上调用管道时,会引发此错误:
But whe I call the pipe on the NavbarMenuComponent template it thows this error:
找不到管道"translate""
'The pipe "translate" could not be found'
如果我在子模块声明中声明该管道有效,但是我需要使该管道成为全局管道,因此当应用程序长大时,我不需要在所有模块中都声明该管道(以及其他全局管道) .有没有办法使管道成为全局管道?
If I declare the pipe in the child module declarations it works,but I need to make the pipe global, so when the app grows up, I don't need to declare this pipe(and other global pipes) in all modules. Is there a way to make the pipe global?
推荐答案
您需要将包含管道(并在declarations: []
和exports: []
中具有管道)的模块添加到
You need to add the module that contains the pipe (and has it in declarations: []
and exports: []
) to imports: [...]
of your current module, then it's available in the current module.
@NgModule({
imports: [ CommonModule],
declarations: [ TranslatePipe],
exports: [ TranslatePipe],
})
export class TranslateModule { }
@NgModule({
imports: [ CommonModule, TranslateModule],
declarations: [ NavbarMenuComponent]
})
export class NavbarModule { }
这篇关于Angular 2中的全局管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!