Cannot Instantiate DatePipe

旧街凉风 提交于 2019-11-27 09:07:27

If you take a look at source code then you will see that DatePipe constructor asks for a required parameter:

constructor(@Inject(LOCALE_ID) private _locale: string) {}

There is no default locale for DataPipe

https://github.com/angular/angular/blob/2.0.0/modules/%40angular/common/src/pipes/date_pipe.ts#L97

That's why typescript gives the error. This way you have to initiate your variable as shown below:

datePipeEn: DatePipe = new DatePipe('en-US')
datePipeFr: DatePipe = new DatePipe('fr-FR')
constructor() {
  console.log(this.datePipeEn.transform(new Date(), 'dd MMMM')); // 21 September
  console.log(this.datePipeFr.transform(new Date(), 'dd MMMM')); // 21 septembre
}

Hope it helps you!

looks everything fine, error must be anywhere else in your code. See my plunker: https://plnkr.co/edit/koDu6YmB131E6sXc6rKg?p=preview

import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {DatePipe} from '@angular/common';

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
    </div>
  `,
})
export class App {

  dPipe = new DatePipe();

  constructor() {
    this.name = 'Angular2'
    console.dir(this.dPipe);
    console.log(this.dPipe.transform(new Date(), 'dd.MM'));
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

And @Harry Ninh .. you can't inject Pipes!!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!