在 es6 class 中为 angular 1.5 控制器定义常量

Defining constants in es6 class for angular 1.5 controller

我正在努力让它发挥作用。我知道静态变量不能在 ES 6 格式的 class 中声明。如何在 class 中声明常量并在 class 本身

中访问它

这就是我所拥有的。我试图在 $onINit 时访问常量的构造函数值。我确实看到 this.constructor.Consts 具有正确的值。但是,当我尝试使用 this.getActionConsts.A 访问它们时,它不存在。

有什么线索吗?

或者有没有更好的定义常量的方法

class ActionCtrl {

    constructor($scope) {
      this.$scope = $scope;
    }

    static get Consts() {
      return {
        A: '5010',
        B: '5020',
        C: '5030'
      };
    }

    getActionConsts() {
      return this.constructor.Consts;
    }

    $onInit() {
      this.Actions = [{
        'id': this.getActionConsts.A,
        'title': '1'
      }, {
        'id': this.getActionConsts.B,
        'title': '1'
      }];
    }
}

您没有在 $onInit() 内部调用 getActionConts。当您将 this.getActionConsts.A 更改为 this.getActionConsts().A 时,它会起作用。您也可以使用 class 名称而不是 this.constructor,这样更简洁。如果您想阅读更多内容,我使用了这些文档 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static

当我使用常量时,我​​只使用 const 声明并在 class 之外声明我的常量。 Angular 也有一些奇特的常量定义方法,我想不起来了。