Angular 2 中的全局管道

2023-11-23

我想让管道在所有应用程序中可用。根据我在 Angular 文档和互联网中读到的内容,如果我在根模块声明中声明一个管道,它会使该管道在所有应用程序中可用。我有这个AppModule代码:

@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";
    }
}

但是当我在导航栏菜单组件模板上调用管道时,它会抛出此错误:

“找不到‘翻译’管道”

如果我在子模块声明中声明管道,它可以工作,但我需要使管道全局化,因此当应用程序长大时,我不需要在所有模块中声明此管道(和其他全局管道)。有没有办法让管道全球化?


您需要添加module包含管道(并将其放在declarations: [] and exports: []) to imports: [...]当前模块的,那么它在当前模块中可用。

@NgModule({
  imports:      [ CommonModule],
  declarations: [ TranslatePipe],
  exports:      [ TranslatePipe],
})
export class TranslateModule { }
@NgModule({
  imports:      [ CommonModule, TranslateModule],
  declarations: [ NavbarMenuComponent]
})
export class NavbarModule { }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular 2 中的全局管道 的相关文章

随机推荐