问题描述
我正在尝试在Angular2应用中实例化 DatePipe
对象以使用 transform(...)
函数
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
// ...
}
此代码该部分在RC5中运行良好。现在,我尝试升级到Angular2最终版本,并在运行 ng serve
或 ng build
时遇到此错误,
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.
如何解决此问题?还有另一种实例化Pipe的方法吗?还是Angular停止支持在组件内部实例化Pipes?
How can I resolve this issue? Is there another way of instantiating a Pipe? Or has Angular stopped supporting instantiating of Pipes inside components?
推荐答案
如果您查看源代码,那么您将看到DatePipe构造函数要求一个必需的参数:
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) {}
DataPipe没有默认语言环境
There is no default locale for DataPipe
这就是打字稿给出错误的原因。
这样,您必须如下所示初始化变量:
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
}
希望它对您有帮助!
这篇关于无法实例化DatePipe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!