use*_*781 19 javascript dependency-injection angularjs
最近我遇到了AngularJS Strict DI模式.使用它的目的和好处是什么?我们是否会通过在移动设备上使用它来获得显着的性能提升?
我尝试将它应用于我的代码,在编写代码时我没有做任何注释.但是,我的代码要缩小,并在构建期间进行ng-annotate.但是为什么在我将严格的DI模式添加到我的代码后,我仍然会收到错误说明"需要明确的注释"?
mor*_*els 34
严格的DI模式在运行时发现一段不符合缩小的代码时,基本上会抛出错误; 但请注意,代码可能是正确的,没有逻辑语法错误.
引用文档:
如果app元素上存在此属性,则将以"strict-di"模式创建注入器.这意味着应用程序将无法调用不使用显式函数注释的函数(因此不适合缩小),如依赖注入指南中所述,有用的调试信息将有助于跟踪这些错误的根.
例如,此代码触发错误,因为($scope, $http, $filter)未使用$inject或向.controller(A,B)方法提供数组作为第二个字段显式注入.
angular.module("myApp", [])
// BadController cannot be invoked, because
// the dependencies to be injected are not
// explicitly listed.
.controller("BadController", function($scope, $http, $filter) {
// ...
});
Run Code Online (Sandbox Code Playgroud)
右片段:
angular.module("myApp", [])
.controller("GoodController1", GoodController1);
GoodController1.$inject = ["$scope", "$http", "$filter"];
function GoodController1($scope, $http, $filter){}
Run Code Online (Sandbox Code Playgroud)
要么:
angular.module("myApp", [])
.controller("GoodController1",
["$scope", "$http", "$filter", function ($scope, $http, $filter){
//...
}]);
Run Code Online (Sandbox Code Playgroud)
为了回答您的问题,使用它没有显着的性能提升.它只授予您微小的错误安全性.这是因为缩小会更改变量名称,例如在$scope没有显式注释的情况下使用时会破坏代码.
Angular strict DI强制执行代码可缩小性.
当您的代码缩小时,参数的名称会缩短,从而打破角度的DI.为了解决这个问题,angular已经添加了两个(现在可能更多)替代方法来添加依赖项.
也许最常见的方式和ng-annotate使用的方法是将数组而不是函数作为第二个参数.依赖项是数组中最后一个元素之前的字符串,字符串是依赖项名称.
controller.$inject(['$scope']);
angular.module('app', ['dependency']).controller('myCtrl', ['myFirstDep',
function(willBeInjectedHere){}])
Run Code Online (Sandbox Code Playgroud)
在使用angular进行检查之前,你的ng-annotate可能没有运行.确保你没有和注释一起运行uglify,明确地执行它.如果您的代码抛出错误,那么很可能在某处没有进行注释.
小智 6
您还可以像这样添加strict-di:
angular.bootstrap(document, ['app'], {
strictDi: true
});
Run Code Online (Sandbox Code Playgroud)
当使用角度流星es6类型的应用程序.
| 归档时间: |
|
| 查看次数: |
13316 次 |
| 最近记录: |