加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular 2中的全局管道

发布时间:2020-12-17 17:22:29 所属栏目:安全 来源:网络整理
导读:我想在所有应用程序中提供管道.根据我在Angular文档和互联网中读到的内容,如果我在根模块声明中声明了一个管道,那么它就是所有应用程序中的管道.我有这个AppModule代码: @NgModule({ imports: [ BrowserModule,NavbarModule],declarations: [ AppComponent,
我想在所有应用程序中提供管道.根据我在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";
    }
}

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

‘The pipe “translate” could not be found’

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

解决方法

您需要将包含管道的模块(并在声明中包含它:[]和exports:[])添加到当前模块的导入:[…],然后在当前模块中可用.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读