【问题标题】:Global pipe in Angular 2Angular 2中的全局管道
【发布时间】:2016-10-24 13:25:32
【问题描述】:

我想让一个管道在所有应用程序中都可用。根据我在 Angular 文档和 Internet 中阅读的内容,如果我在根模块声明中声明了一个管道,它将使管道在所有应用程序中都可用。我有这个 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";
    }
}

但是当我在 NavbarMenuComponent 模板上调用管道时,它会出现此错误:

'找不到管道“翻译”'

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

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    您需要将包含管道的模块(并在declarations: []exports: [] 中)添加到当前模块的imports: [...],然后它在当前模块中可用。

    @NgModule({
      imports:      [ CommonModule],
      declarations: [ TranslatePipe],
      exports:      [ TranslatePipe],
    })
    export class TranslateModule { }
    
    @NgModule({
      imports:      [ CommonModule, TranslateModule],
      declarations: [ NavbarMenuComponent]
    })
    export class NavbarModule { }
    

    【讨论】:

    • 我用您的回复更新了代码,我在 AppModule 的导出中添加了管道,然后将 AppModule 导入到“NavBarModule”导入中,但现在它引发了另一个错误:“使用预期值”未定义" 由模块 "NavbarModule"' 导入。
    • 最好为管道创建一个共享功能模块,而不是在其他模块中导入AppModule。模块(在你的情况下AppModule 需要导出TranslatePipe
    • 我工作。所以最后,我必须逐个模块地导入我想要的所有东西,不是吗?
    • 无论如何,使用通用功能模块而不是逐个添加管道、服务等是个好主意。谢谢!
    • 嘿抱歉评论,由于缺乏对 Angular2 的了解,这只是一个错误的问题。很抱歉给您带来麻烦,感谢您的宝贵时间。
    猜你喜欢
    • 1970-01-01
    • 2017-03-09
    • 1970-01-01
    • 2017-08-27
    • 2017-01-16
    • 2016-08-02
    • 2017-05-16
    • 2017-03-11
    相关资源
    最近更新 更多