Failed to create DatePipe.

I am trying to instantiate a DatePipe object in my Angular2 application to use the transform(...) function in the component that I am developing.

 // ... import { DatePipe } from '@angular/common'; @Component({...}) export class PanelComponent implements OnInit { // ... datePipe: DatePipe = new DatePipe(); // Error thrown here // ... } 

This code segment worked great in RC5. Now I am trying to upgrade to Angular2 final release and get this error when I run ng serve or ng build ,

 ~/tmp/broccoli_type_script_compiler-input_base_path-XitPWaey.tmp/0/src/app/panel/panel.component.ts (33, 24): Supplied parameters do not match any signature of call target. 

How can I solve this problem? Is there any other way to instantiate a pipe? Or did Angular stop supporting Pipes instantiation inside components?

+5
source share
2 answers

If you look at the source code, you will see that the DatePipe constructor asks for the 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

This is why typescript gives an error. Therefore, you should 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 this helps you!

+14
source

looks good, the error should be somewhere else in your code. See my pluker: 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 cannot enter Pipes !!

0
source

All Articles