[英]How to keep injected dependencies private in AngularJS Controllers with ES6 Class
I know that my question is related to this post , but I wonder if there is an AngularJS specific way to address this issue. 我知道我的问题与这篇文章有关 ,但我想知道是否有一种AngularJS特定的方法可以解决这个问题。
Here is the deal: 这是交易:
I'm using ES6 Class and ControllerAs
in my Angular directives, so controllers are declared like so: 我在Angular指令中使用ES6 Class和
ControllerAs
,因此控制器声明如下:
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
}
The thing is that I want to have access to my dependency injections in all classe methods, but I don't want them to be reachable publicly from the outside. 问题是我希望能够在所有classe方法中访问我的依赖注入,但我不希望它们可以从外部公开访问。
Moreover I don't want to declare my methods in the constructor as I don't want them to be redeclared for each instance. 此外,我不想在构造函数中声明我的方法,因为我不希望它们被重新声明为每个实例。
Is there a proper way to do this or am I missing something ? 有没有正确的方法来做到这一点,还是我错过了什么?
If you want to keep injectables private, use classical angular controller structure, like this 如果您想将注射剂保密,请使用经典的角度控制器结构,如下所示
function MyCtrl($log) {
'ngInject';
this.logSomething = function(message) {
$log(message);
}
}
Now actual $log
is hidden in closure, but logSomething
publicly available for templates. 现在实际的
$log
隐藏在闭包中,但logSomething
公开用于模板。
UPD. UPD。 If you want to keep using ES6 classes for some reason, you can try to use any existing methods to make some class member as private.
如果由于某种原因想继续使用ES6类,可以尝试使用任何现有方法将某些类成员设置为私有。 There is a review of possible ways to do it.
有可能的方法进行审查 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.