【问题标题】:Any difference between angular $inject property and inline array annotation?角度 $inject 属性和内联数组注释之间有什么区别?
【发布时间】:2017-03-06 20:39:12
【问题描述】:

阅读angular docs on dependency injection,有两种适合缩小的方法:

  • 内联数组注释: module.factory("MyStuff",['dependency',function(dep){...}])
  • $inject 属性: function MyStuff(dep) {...} MyStuff.$inject = ['dependency']; module.factory("MyStuff",MyStuff);

推荐使用内联的(第一个)。在我的一个项目中,风格指南坚持使用$inject 属性。我还经常在开源代码中看到$inject 属性形式。

因此问题:

使用$inject 属性表单有哪些实际或技术优势?

我想出了两个,但它们看起来不太合法:

  • 直接创建MyStuff 的实例: new MyStuff(someOtherDependency).foo(...);
  • console.log(myStuffInstance) 中有函数名

还有什么我遗漏的吗?

【问题讨论】:

  • 为了可读性,建议保持清晰的关注点分离。
  • 刚刚有人评论了ng-annotate (github.com/olov/ng-annotate),值得一提...
  • 是的,ng-anotate 用于为生产模式自动添加压缩友好注入的任务,因此您不必添加 ['$scope', ..., function ($scope, ...]myFactory.$inject['$scope, ...。在构建到生产环境时,它会添加对缩小友好的注入。

标签: javascript angularjs dependency-injection inject


【解决方案1】:

您应该使用ng-annotate。如果您正在使用构建工具(应该),请将 ng-annotate 插件与您的构建工具一起使用。

第二种方法的主要好处是它对模块友好。

class MyClass {
    constructor($q) {}
}

MyClass.$inject = ['$q']

module.exprots = MyClass

你可以像普通类一样使用它

const MyClass = require('./myclass')
const foo = new MyClass($q)

或将其交给 angular

angular.service('MyClass', MyClass)

你真的做不到

module.exports = ['$q', MyClass]

因为它会使 require('./myclass') 在 Angular 之外无法使用


但如果你不使用模块或 OOP,第一种方法更容易

angular.service('MyClass', ['$q', function ($q) {}])

没有必要为它创建一个类

【讨论】:

    猜你喜欢
    • 2011-04-16
    • 1970-01-01
    • 1970-01-01
    • 2013-02-25
    • 2011-11-25
    • 2011-08-18
    • 2021-07-11
    • 1970-01-01
    相关资源
    最近更新 更多