【发布时间】:2016-06-18 23:06:26
【问题描述】:
我的 Angular2 应用程序中有一堆枚举,我为每个枚举创建了一个相应的 utils 类,它提供了一些额外的功能。这只是绕过了 TypeScript 的限制,即我无法像在 Java 中那样向枚举添加函数。
下面是我的国家枚举和对应的utils类的例子:
import {Injectable} from "@angular/core";
export enum Country {
ANDORRA = <any>"ANDORRA",
UNITED_ARAB_EMIRATES = <any>"UNITED_ARAB_EMIRATES",
AFGHANISTAN = <any>"AFGHANISTAN",
// ...
// more countries skipped for brevity
// ...
ZAMBIA = <any>"ZAMBIA",
ZIMBABWE = <any>"ZIMBABWE"
}
@Injectable()
export class CountryUtils {
private _emptyEntry: Array<string> = ["", "", ""];
private countryData: any = {
ANDORRA: ["Andorra", "AD", "AND"],
UNITED_ARAB_EMIRATES: ["United Arab Emirates", "AE", "ARE"],
AFGHANISTAN: ["Afghanistan", "AF", "AFG"],
// ...
// more countries skipped for brevity
// ...
ZAMBIA: ["Zambia", "ZM", "ZMB"],
ZIMBABWE: ["Zimbabwe", "ZW", "ZWE"]
}
getData(country: Country): any {
if (!country) {
return this._emptyEntry;
}
return this.countryData[Country[country]];
}
getName(country: Country): any {
return this.getData(country)[0];
}
getCode2(country: Country): any {
return this.getData(country)[1];
}
getCode3(country: Country): any {
return this.getData(country)[2];
}
}
现在,如您所见,我已将 utils 类标记为 Injectable,以便可以在需要的地方将其与 DI 一起使用。
我面临的问题是这些枚举也用于我的核心 TS/JS 模型类中,这些模型类不依赖于 Angular2,因此我不能使用 DI 注入我的 utils 类的实例(如上面的那个)在核心模型类中。
我看到的唯一解决方法是放弃 Injectable() 方法并将 utils 类中的方法标记为静态。所以这样我就可以将每个 utils 类与枚举一起导入并在任何我想要的地方使用它。
我的问题是,这样的设计决策有多糟糕?在 Angular2 中做这样的事情是可以接受的,还是完全禁止使用静力学?与常规 DI 方法相比,我看不到任何特别有害的东西,就像眼睛疼痛一样。
非常感谢任何建议。提前致谢!
【问题讨论】:
标签: enums typescript static angular enumeration