javascript - 如何使用 ES6 类在 AngularJS Controller 中保持注入(inject)的依赖项私有(private)

标签 javascript angularjs dependency-injection ecmascript-6

我知道我的问题与 this post 有关,但我想知道是否有特定于 AngularJS 的方法来解决这个问题。

这是交易:

我在我的 Angular 指令中使用 ES6 Class 和 ControllerAs,所以 Controller 声明如下:

class myCtrl {
  constructor ( $log ) {
    'ngInject';

    // Dependency Injections
    var privateLog  = $log;      // Private but scoped to constructor
    this.publicLog  = $log;      // Public

    // Default attributes
    this.foo = 'bar';

    this.publicLog.log('it works in constructor');  // logs 'it works in constructor'
    privateLog.log('it works in constructor');      // logs 'it works in constructor'
  }

  logSomething () {
    this.publicLog.log('it works in class method'); // logs 'it works in class method'
    try {
      privateLog.log('it works in class method');
    }
    catch(e) {
      console.log(e);                               // Uncaught ReferenceError: privateLog is not defined
    }
  }
}

var test = new myCtrl();

test.logSomething();
test.publicLog.log('is public');      // logs 'is public' 
try {
  test.privateLog.log('is private');
}
catch(e) {
  console.log(e);                     // Uncaught TypeError: Cannot read property 'log' of undefined
}

问题是我想在所有类方法中访问我的依赖注入(inject), 但我不希望它们可以从外部公开访问。

此外,我不想在构造函数中声明我的方法,因为我不想为每个实例重新声明它们。

是否有正确的方法来执行此操作,还是我遗漏了什么?

Here is the Fiddle

最佳答案

如果你想保持注入(inject)器的私密性,使用经典的 Angular Controller 结构,就像这样

function MyCtrl($log) {
   'ngInject';
   this.logSomething = function(message) {
       $log(message);
   }
}

现在实际的 $log 隐藏在闭包中,但是 logSomething 对模板公开可用。

UPD。如果你出于某种原因想继续使用 ES6 类,你可以尝试使用任何现有的方法将一些类成员设为私有(private)。有 a review可能的方法。

关于javascript - 如何使用 ES6 类在 AngularJS Controller 中保持注入(inject)的依赖项私有(private),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35312735/

相关文章:

java - 创建用于收集数据的搜索插件

javascript - 单击时无法调用函数

jquery - 一次变灰多个相同 css 类的标签

angular - 在 NgModule 中使用实例化依赖

c# - 使用 WCF 服务注入(inject) - Dispose() 未触发

javascript - 开发购物优惠 chrome 扩展的最佳方式是什么?

Javascript 已加载但在 WordPress 中未触发

javascript - IntelliJ 13 提示内联脚本中的 'unescaped xml character'

javascript - 数据未显示在流程图中(metronic 主题)

java - 如何使用 Dagger2 将依赖项注入(inject)任何类型的对象?