You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular项目中Constants类成员始终为undefined问题排查

问题解决:Angular中Constants类静态常量返回undefined的原因

你的Constants类存在一个低级语法错误:dateTimeFormat和dateFormat这两个静态成员只做了类型声明,没有实际赋值,导致引用时始终返回undefined。

原代码的问题点

export class Constants
{
    public static CLEANER_STR= 'Cleaner'; // ✅ 正确赋值,有实际值
    public static dateTimeFormat: 'yyyy-MM-dd HH:mm'; // ❌ 仅类型标注,未赋值,默认undefined
    public static dateFormat: 'yyyy-MM-dd'; // ❌ 同样问题
};

这里的: 'yyyy-MM-dd HH:mm'是TypeScript的字面量类型约束,只限定了属性的类型范围,但没有给属性赋予具体值,所以这两个静态成员的默认值是undefined。

修正后的代码

把类型标注的冒号:改成赋值的等号=即可:

export class Constants
{
    public static CLEANER_STR = 'Cleaner';
    public static dateTimeFormat = 'yyyy-MM-dd HH:mm'; // ✅ 赋值后有实际字符串值
    public static dateFormat = 'yyyy-MM-dd'; // ✅ 同样修改
};

修改后,组件里引用Constants.dateTimeFormat就能获取到正确的格式化字符串,不会再出现undefined的问题。

内容的提问来源于stack exchange,提问作者janci

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 03:32:34