如何在 Angular AOT 中使用枚举(在单独的文件中)?

How to use enum (within separate file) with Angular AOT?

将基于 angular 的应用程序 (angular-cli) 从运行良好的基于​​ JIT 的场景转换为基于 AOT 的场景。 AOT 构建 运行 很好。

打开生成的网页时,我收到 无法读取 属性 'none' of undefined 错误。这些错误是由运行时未定义的枚举引起的。

非常简化的示例(有 2 个单独的文件)

action-type.enum.ts(单独文件中的枚举)

export enum eActionType {
    none,
    actionA
    ...
}

test.component.ts(单独文件中的组件)

import { eActionType } from './action-type.enum';

@Component({ ... })
export class Test {

    // @Runtime eActionType (eActionType.none) will be undefined
    private/protected/public actionType: eActionType = eActionType.none;
}

eActionType 在 test.component.ts 中不可用,尽管正在导入。

可能的解决方案 1 - 在同一文件中枚举(不可取)

test.component.ts

// Exported enum within same file
export enum eActionType {
    none,
    actionA
    ...
}

@Component({ ... })
export class Test {

    // @Runtime eActionType is available
    private/protected/public actionType: eActionType = eActionType.none;
}

如果在同一文件中声明枚举,它将在运行时正常工作。但这是不可取的,因为与可以导入多个位置的外部文件中的枚举相比,会失去可维护性。

可能的解决方案 2 - class 使用静态属性而不是枚举 (也不理想)

action-type.enum.ts(单独文件中的枚举)

export class eActionType {
    static none    = 0;
    static actionA = 1;
    ...
}

test.component.ts(单独文件中的组件)

import { eActionType } from './action-type.enum';

@Component({ ... })
export class Test {

    // @Runtime eActionType is available as static property of eActionType        
    private/protected/public actionType: eActionType = eActionType.none;
}

也没有真正漂亮的解决方案,但至少只有声明以前的枚举,而不是消费者代码必须在所有情况下都更改。

如何强制在运行时在其他位置访问外部文件中声明的正确枚举?

让你的变量 public.

public actionType: eActionType = eActionType.none;

解法:

  • 完全空node_modules
  • npm 安装然后开始...

我花了好几天时间,阅读了所有我能找到的东西(非真正相关的),修改了我的代码一百次。

巧合的是,我意识到 ng 的脚手架正在抛出错误消息(服务和构建没有)。清理一切,进行全新的 npm 安装——突然间,所有应该开箱即用的东西都开箱即用了。不敢相信我浪费了几天。 (将保留该问题原样,因为它可能会给其他人一个提示)

如果出现不该出现的错误并且网络上没有其他人报告相同的问题,请保持警惕并首先寻求最简单的解决方案:

-> 进行全新安装