1

In my opinion, if A.module import B.module and B.module import C.module, it stand that A.module import C.module. That's the reason why many Angular developers build a public module named Shared.module.

However, this rule looks like doesn't apply to DatePipe. I have builded a Shared.module, the CommonModule is imported and exported in this module. Then I import the Shared.module in AppModule. The official document tell me the DatePipe is belongs to CommonModule.

Unfortunately, the browser console shows error: NullInjectorError: "StaticInjectorError(AppModule)[AppComponent -> DatePipe]:

You can see the code in below link.

https://stackblitz.com/edit/angular-common-datepipe?embed=1&file=src/app/app.component.ts

Who can help me to figure out this problem?

Eve-Sama
  • 2,176
  • 4
  • 20
  • 32
  • instead of providing `DatePipe` to the constructor, you could declare it as a member variable as follows: `readonly datePipe = new DatePipe('en-US');` – uminder Jul 08 '19 at 10:35

2 Answers2

6

What you said is correct. The reason for the above cause is that in CommonModule, DatePipe is not registered as a provider.

What you can do is adding DatePipe as a provider in your shared module.

providers: [DatePipe]
Dulanjaya Tennekoon
  • 2,408
  • 1
  • 18
  • 31
2

Pipes are not injectable in Angular. You have to manually provide them yourself.

@NgModule({
   declarations: [AppComponent],
   providers: [DatePipe]
   // ....
{)
export class AppModule {}
Reactgular
  • 52,335
  • 19
  • 158
  • 208