子组件中不使用重写的角管

问题描述 投票:0回答:1

我压倒Angular的内置date管道,包括更好的i18n日期。我在一个“工具箱”项目中实现了管道,该项目后来作为主项目中的依赖项包含在内。我将新管道包裹在一个模块中:

import { NgModule } from '@angular/core';
import { DateProxyPipe } from './dateproxy.pipe';

@NgModule({
    declarations: [
        DateProxyPipe
    ],
    exports: [
        DateProxyPipe
    ]
})
export class PipesModule { }

在主项目的app.module.ts中,我导入该模块并在提供者中设置它:

import { PipesModule } from '../../../src/pipes/pipes.module';

@NgModule({
  imports: [
    ...
  ],
  entryComponents: [
    ...
  ],
  declarations: [
    AppComponent,
    GraphLegendComponent,
    TimeComponent,
    ...,
    DateProxyPipe
  ],
  providers: [
    DateProxyPipe,
    ...
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

这在直接使用时效果很好,例如,当我更改语言时,我在上面列表中留下的TimeComponent模板中的{{selectedTimespan.from | date:'medium'}}以不同的格式显示,就像我想要的那样。

但它在子组件中不起作用 - 即在列出的GraphLegendComponent的子组件的模板中使用的日期管道不会像TimeComponent中那样改变。

我尝试在各种位置声明,导入,提供DateProxyPipe,但无法使其工作。我究竟做错了什么?

编辑:其中一个子组件是TimespanShiftSelectorComponent。这是它的模块:

import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

...
import { TimespanShiftSelectorComponent } from './timespan-shift-selector/timespan-shift-selector.component';

const COMPONENTS = [
  ...,
  TimespanShiftSelectorComponent
];

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    ...
  ],
  declarations: [
    COMPONENTS,
  ],
  exports: [
    COMPONENTS
  ],
  providers: [
    ...
  ]
})
export class TimeModule {
}
angular override angular-pipe
1个回答
1
投票

实际上很简单,问题是你没有将PipesModule导入到你的所有模块中。只需将其导入AppModule,就不允许功能模块访问PipesModule的内容。

我建议您创建一个SharedModule,您可以导入和导出PipesModule以及您需要共享的任何其他内容(不包括组件模块,因为它将创建循环依赖)。

对于组件,创建另一个ComponentModule并导入和导出组件模块。

现在,在您的功能模块中,只需导入SharedModuleComponentsModule,即可随时随地访问所有内容。

这是我正在使用的SharedModule的一个例子:

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    RouterModule,

    // 3rd party
    DirectivesModule,
    LoadingBarHttpClientModule,
    PipesModule,
    TranslateModule
  ],
  exports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    RouterModule,

    // 3rd party
    DirectivesModule,
    LoadingBarHttpClientModule,
    PipesModule,
    TranslateModule
  ]
})

export class SharedModule {}

和一个ComponentsModule

import {COMPONENTS} from '../components/components';
import {COMPONENTS_PROVIDERS} from '../components/providers';

@NgModule({
  imports: [
    COMPONENTS
  ],
  exports: [
    COMPONENTS
  ]
})

export class ComponentsModule {

  public static forRoot() {

    return {
      ngModule: ComponentsModule,
      providers: COMPONENTS_PROVIDERS
    };
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.