CodeQL 文档

不兼容的依赖注入

ID: js/angular/incompatible-service
Kind: problem
Security severity: 
Severity: error
Precision: high
Tags:
   - correctness
   - frameworks/angularjs
Query suites:
   - javascript-security-and-quality.qls

点击查看 CodeQL 仓库中的查询

AngularJS 内置支持依赖注入:组件只需列出它们所依赖的服务的名称,AngularJS 就会在运行时提供合适的实例并将它们作为参数传递。

每个注入的服务都有一个类型,这个类型会影响该服务与哪些组件兼容。

建议

确保声明的依赖项具有与注入它们的组件正确的类型。

示例

以下示例显示了一个 config 方法,它列出了对名为 year 的服务的依赖关系。后来,定义了一个类型为 value 的服务,其名称为 year。这是不允许的,因为 config 方法只能注入类型为 providerconstant 的服务。

angular.module('myModule', [])
    .config(['year', function(year) {
        // ...
    }]);

angular.module('myModule')
    .value('year', 2000); // BAD: year is of kind 'value'

为了解决这个问题,year 服务必须是类型为 constant

angular.module('myModule', [])
    .config(['year', function(year) {
        // ...
    }]);

angular.module('myModule')
    .constant('year', 2000); // GOOD: year is of kind 'constant'

参考资料

  • ©GitHub, Inc.
  • 条款
  • 隐私