【问题标题】:Angular - property '$inject' does not exist on type error in VS2015Angular - VS2015中的类型错误不存在属性'$inject'
【发布时间】:2018-06-13 17:23:57
【问题描述】:

当我将 AngularJS 项目升级到 Angular 4 时,我在 Visual Studio 2015 中遇到了数千个编译器错误。我已将该应用程序转换为可以成功运行 AngularJS 代码的混合应用程序与Angular4代码一起。使用CLI编译,typescript编译成功,app正常运行。

大多数错误在 *.d.ts 文件中,但在 *.ts 文件中也有一些错误。我想知道 *.ts 中的错误是否会阻止正确编译,以及是否会导致 *.d.ts 文件中的其他错误。

当我有这样的东西(使用 AngularJS 代码)时,*.ts 文件中会出现一种错误类型:

myCtrl.$inject = ['$window'];

我收到此错误:

Property '$inject' does not exist on type 'typeof myCtrl'

假设我需要修复这个特定错误(并且这不仅仅是导致 $inject 无法识别的其他编译问题),我需要做什么?这是我的一个有错误的 *.ts 文件的完整代码:

(function() {

class myCtrl {

    window: any;

    constructor($window, $location) {
        this.window = $window;
    }

    myMethod(myParameter) {
        ... do stuff
    }
}

// *****error on this line*******
myCtrl.$inject = ['$window'];

class myDirective {

    restrict: string;
    controller: string;
    controllerAs: string;
    templateUrl: string;
    $document: any;
    $window: any;
    instance: any;

    constructor($document, $window) {
        this.restrict       = 'E';
        this.controller     = 'myCtrl';
        this.controllerAs   = 'myCtrlAlias';
        this.templateUrl    = '/yadda.html';
        this.$document      = $document;
        this.$window        = $window;
    }
    static myFactory($document, $window) {
        var instance = new myDirective($document, $window);
        return instance;
    }
}

angular
    .module('myModule', ['myDependency'])
    .directive('mainNav', ['$document', '$window', myDirective.myFactory])
    .controller('myCtrl', myCtrl);
})();

这是我的 tsconfig.json。我正在使用 tsc 1.8

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es2015", "dom" ],
    "noImplicitAny": false,
    "suppressImplicitAnyIndexErrors": true,
    "noStrictGenericChecks": true
  },
  "include": [ "**/*.ts" ],
  "exclude": [
    "node_modules"
  ]
}

【问题讨论】:

    标签: angularjs typescript dependency-injection


    【解决方案1】:

    分配类静态和prototype属性直接导致TypeScript中的类型错误,因为有一些限制

    TypeScript 天生就支持类字段。应该是:

    class myCtrl {
        static $inject = ['$window'];
    
        constructor($window, $location) { ... }
        ...
    }
    

    这也允许在构造函数上方有 DI 注释并避免 DI 错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-04
      • 1970-01-01
      • 1970-01-01
      • 2019-07-06
      • 2023-03-18
      • 2021-10-22
      • 2021-12-01
      相关资源
      最近更新 更多