【问题标题】:Issues converting angular 1.x controller to TypeScript将 Angular 1.x 控制器转换为 TypeScript 的问题
【发布时间】:2016-01-11 14:41:36
【问题描述】:

TypeScript 新手并尝试从 js 转换为 ts(使用 angular 1.x)。这是一个控制器。转换为 ts 时遇到问题。 “模块”是 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”类型上不存在属性“内容”。
错误 TS2339:“IStateProvider”类型上不存在属性“当前”。

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

【问题讨论】:

  • 什么是行不通的?
  • 发现了我的第一个问题。正在使用 IStateProvider 而不是 IStateService。
  • 对于“内容”错误,是否需要显式声明类成员?与 js 不同,这在 TypeScript 中是必需的吗?
  • @Ed.S.是的,只需在构造函数上方(或下方)添加 content: any

标签: javascript angularjs typescript angular-ui-router


【解决方案1】:

“AboutController”类型上不存在属性“内容”

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

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

类型“IStateProvide”上不存在属性“当前”

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-11
    • 2019-09-17
    • 2023-03-21
    • 2018-01-15
    • 1970-01-01
    • 1970-01-01
    • 2017-12-11
    • 2016-08-23
    相关资源
    最近更新 更多