61

I tried to use DatePipe in my service like this:

import { Injectable } from '@angular/core';
import { DatePipe } from '@angular/common';
import { TranslateService } from '@ngx-translate/core';

@Injectable({
   providedIn: 'root',
})
export class BaseService {

    public items = [];
    constructor(
        protected datePipe: DatePipe,
        protected translateService: TranslateService
    ) { }
}

But I get this error: NullInjectorError: No provider for DatePipe!". What is the cause?

Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38
frint
  • 771
  • 1
  • 7
  • 14
  • do you import the commonModule in your application module ? https://angular.io/api/common/CommonModule – Pac0 Oct 24 '19 at 11:42
  • You can only inject classes decorated with `@Injectable`. If you need to use a pipe in a component (as opposed to a template) instantiate a `new` instance. – The Head Rush Oct 24 '19 at 11:52
  • See it on [Stack Blitz](https://stackblitz.com/edit/angular-date-pipe-lc?embed=1&file=src/app/app.module.ts) – lealceldeiro Oct 24 '19 at 11:53

1 Answers1

132

Just add the DatePipe in the NgModule providers section in your app.module.ts file.

import { DatePipe } from '@angular/common';

...

@NgModule({
  declarations: [...],
  imports: [...],
  providers: [
    DatePipe,
    ...
  ],
  bootstrap: [AppComponent]
})
Guileas
  • 61
  • 5
MonkeyScript
  • 4,776
  • 1
  • 11
  • 28