gpt4 book ai didi

angular - 无法实例化 DatePipe

转载 作者:太空狗 更新时间:2023-10-29 17:11:51 25 4
gpt4 key购买 nike

我正在尝试在我的 Angular2 应用程序中实例化一个 DatePipe 对象,以便在我正在开发的组件中使用 transform(...) 函数。

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

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

此代码段在 RC5 中运行良好。现在我正在尝试升级到 Angular2 最终版本并在运行 ng serveng 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.

我该如何解决这个问题?还有另一种实例化管道的方法吗?或者 Angular 是否已停止支持在组件内实例化管道?

最佳答案

如果您查看源代码,您会发现 DatePipe 构造函数要求提供必需的参数:

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

DataPipe 没有默认语言环境

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

这就是 typescript 给出错误的原因。这样,您必须启动您的变量,如下所示:

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
}

希望对你有帮助!

关于angular - 无法实例化 DatePipe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39607568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com