由于我有一个 C# 后端,所以我想到将 C# 原理应用到 Angular 前端,所以我想出了这个:
declare interface Date {
addDays(days: number): Date;
addYears(years: number): Date;
isToday(): boolean;
isSameDate(date: Date): boolean;
customFormat(): string;
}
declare interface String {
ToDate(): Date;
}
declare interface Array<T> {
ToDate(): string[];
}
Array.prototype.ToDate = function (): string[] {
return this.valueOf().map(timestamp => timestamp.ToDate());
};
String.prototype.ToDate = function (): Date {
return new Date(this.valueOf());
};
Date.prototype.addDays = function (days: number): Date {
if (!days) return this;
let date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
};
Date.prototype.addYears = function (years: number): Date {
if (!years) return this;
let date = new Date(this.valueOf());
date.setFullYear(date.getFullYear() + years);
return date;
};
Date.prototype.isToday = function (): boolean {
let today = new Date();
return this.isSameDate(today);
};
Date.prototype.isSameDate = function (date: Date): boolean {
return date && this.getFullYear() === date.getFullYear() && this.getMonth() === date.getMonth() && this.getDate() === date.getDate();
};
Date.prototype.customFormat = function (): string {
let date = new Date(this.valueOf());
let yyyy = date.getFullYear();
let mm = date.getMonth() + 1;
let dd = date.getDate();
return dd + "/" + mm + "/" + yyyy;
};
我的想法是我可以做类似的事情
let foo = new Date();
foo.addYears(10);
这基本上就是扩展在 C# 中的工作方式。 问题是这些原型扩展在开发过程中可以工作,但看起来它们一旦投入生产就消失了。
在某些时候,我尝试将所有内容声明为全局的,如下所示:
export {};
declare global {
interface Date {
addDays(days: number): Date;
addYears(years: number): Date;
isToday(): boolean;
isSameDate(date: Date): boolean;
customFormat(): string;
}
}
declare global {
interface String {
ToDate(): Date;
}
}
declare global {
interface Array<T> {
ToDate(): string[];
}
}
// etc
无济于事。
我还尝试在脚本标签中导入index.html中的文件date.extensions.ts,但仍然不起作用。
我也看了this,但我真的不知道在答案的最后一步中应该在哪里使用 import 语句。
如何使扩展按预期工作?
不确定它是否真的可以算作答案,特别是对于“我怎样才能完成这项工作”这个问题,但这是我的经验......
我最初是这样做的。我设置了它,以便构造函数具有额外的覆盖,并且我的类型具有类似扩展的功能。
例如我可以用我的自定义内容
Date
新建一个 new Date('...');
,然后用我的扩展 dt.AddDays(1)
做一些事情。
但是,一开始设置起来很痛苦,因为你需要做整个全局的事情才能让它在整个应用程序中识别它,而且这样做也不是很好,因为你侵犯了类的基本工作方式并且最终可能会与他们(可能)在那里拥有的现有或未来功能发生冲突。
使用一段时间后,它停止了对 Angular 或 TypeScript 本身的一些更新,我一直不知道是哪一个。 还停止了几个项目的工作,但继续为其他几个项目工作;我从来没有弄清楚为什么会这样,也从来没有让坏掉的东西再次工作。
相反,我节省了自己的精力,只是制作了我可以使用的静态帮助器类。不太好,但它仍然包装了您的相关功能,以便您可以使用它们。只是……没那么好。 (忽略有关使用静态方法与可注入服务的任何讨论......)
export class DateHelper {
public static addDays(dt: Date, days: number): Date {
//...
}
}
public doSomething(): void {
let dt = ...;
dt = DateHelper.addDays(dt, 1);
// ...
}
已经足够好了。例如,它为我们提供了一个地方来包装所有日期函数,这样我们就不会直接使用 Date 对象。 当时刻变暗并被 luxon 取代时非常有用 - 一个可以更改日期函数的地方,对应用程序的其余部分进行零更改。
添加提示:由于 C#,我们也有同样的想法,就像您一样 - 因此,我们的 DateHelper 包装器包含一个
toString
方法,它将给定的 C# 类型 ToString
格式更改为相关时刻(原始),然后更改为 luxon字符串格式,因为它们都略有不同。然而,有了这个,我们就可以在 UI 中使用 C# 日期 ToString
格式,以便它们在前端和后端之间保持一致。