Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

angular - Cannot Instantiate DatePipe

I am trying to instantiate a DatePipe object in my Angular2 app to use transform(...) function in a component I'm developing.

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

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

This code segment worked fine in RC5. Now I am trying to upgrade to Angular2 final release and getting 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 resolve this issue? Is there another way of instantiating a Pipe? Or has Angular stopped supporting instantiating of Pipes inside components?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...