是否有可能从Angular中的服务获取枚举的值

问题描述 投票:0回答:1

我创建了一个枚举,目前该枚举是键和动态值,但现在它的值需要来自服务作为显示文本,并且无论如何我都找不到如何做到的。我只需要从服务获取的值就不会更改动态,而该值只是文本的一个值这是枚举。

const enum Test {
Test1 = 'this is test 1',
Test2 = 'this is test 2',
Test3 = 'this is test 3',
Test4 = 'this is test 4',
}

[从现在开始,文本来自另一个平台,其URL例如需要在插值或属性绑定中显示。

Test1 = this.textService.getText('here the id of the text'),

Service中的getText方法

public getText(key: string, isGeneralKey = false): string {
  let searchKeys: string[];
  let result: string | DisplayTextMap;

  searchKeys = key.split('.');
  result = (isGeneralKey
    ? this.generalTexts[searchKeys[0]]
    : this.texts[searchKeys[0]]) as DisplayTextMap;

  if (result && searchKeys[1]) {
    result = result[searchKeys[1]];
  }
  if (result) {
    return this.decodeUnicodeTextService.getDecodedText(result as string);
  }
  return `${key} not found`;
}
angular typescript enums angular-services
1个回答
0
投票

A const enum完全不能具有计算成员。不是const enum的数字enum可以具有计算成员,但不幸的是,具有字符串成员的const不能具有计算成员。我不知道是否有很好的文档,但是至少有一个enum关于您收到的错误消息是如何引起误解的。无论如何,要点是:您无法使用open issue来执行此操作。

幸运的是,您可能真的不需要enum。通常,您可以将enum属性替换为enum对象,并用const属性初始化为您关心的值,例如:

readonly

((上面的 const asReadonly = <T>(t: T): { readonly [K in keyof T]: T[K] } => t const Test = asReadonly({ Test1: this.textService.getText('here the id of the text'), Test2: this.textService.getText('here is a different id'), Test3: this.textService.getText('you get the idea'), Test4: this.textService.getText('etc') }); 仅使属性在编译时为只读。如果还希望在运行时为只读,则可以使其返回asReadonly()而不是Object.freeze(t)。]

然后您可以像使用t值那样使用Test的属性:

enum

const someVal = Test.Test2; // string 对象和const之间存在一些差异,但是它们对于您的用例可能并不重要。如果这样做的话,您可能可以修复它们。

例如:enum引入了命名的types以及命名的值。但是,由于您的值是经过计算的,因此您不能比使用enum作为类型更好。如果要防止某人将随机string值复制到您希望枚举的位置,则可以使用string类型:

branded primitive

然后您可以将const asEnum = <T, N extends string>(t: T, n: N) => Object.freeze(t) as { readonly [K in keyof T]: T[K] & { __brand: N } }; const Test = asEnum({ Test1: this.textService.getText('here the id of the text'), Test2: this.textService.getText('here is a different id'), Test3: this.textService.getText('you get the idea'), Test4: this.textService.getText('etc') }, "Test"); type Test = typeof Test[keyof typeof Test]; 既用作具有属性的值,又用作类型:

Test

无论如何,希望能有所帮助。祝你好运!

function acceptTestEnumOnly(t: Test) { } acceptTestEnumOnly(Test.Test3); // okay acceptTestEnumOnly("oops"); // error! "oops" is not assignable to Brand<"Test">

© www.soinside.com 2019 - 2024. All rights reserved.