将角度1.x控制器转换为TypeScript

时间:2015-10-13 18:04:31

标签: javascript angularjs typescript angular-ui-router

TypeScript新手并尝试将js转换为ts(使用角度1.x)。这是一个控制器。有问题转换为ts。 “module”是ui-router状态提供程序上的自定义数据元素。

(function(module) {
    "use strict";
    module.controller("aboutController", [
        "$state",
        function($state) {
            var vm = this;
            // pass the module to the service to get the content for the about page
            // $state.current.data.module
            vm.content = $state.current.data.module;
        }
    ]);
} (angular.module("app.ui")));

我最近尝试使用ts:

module myApp.ui {
    "use strict";
    class AboutController {
        constructor(private $state: ng.ui.IStateProvider) {
            this.content = $state.current.data.module;
        }
    }
    angular.module("app.ui").controller("aboutController", AboutController);
}

错误
错误TS2339:类型'AboutController'上不存在属性'content' 错误TS2339:类型'IStateProvider'上不存在属性'current'。

修复
(1)我本来应该使用IStateService,而不是IStateProvider - 解决'当前'错误,上面#2。 (2)添加行'public content:string;'在ctor之上 - 解决了'内容'错误,上面#1。 Thx @Brocco

1 个答案:

答案 0 :(得分:2)

  

'AboutController'

类型中不存在属性'content'

您需要在TypeScript中声明所有类属性:

class AboutController {
    content: any; // property declaration
    constructor(private $state: ng.ui.IStateProvider) {
        this.content = $state.current.data.module;
    }
}
  

'IStateProvide`

类型中不存在属性'current'

使用IStateService。注意:这些通常是服务,无论如何都要注入,后缀是一致的。