javascript - 在 Angular 1.5 中使用 Typescript

标签 javascript angularjs typescript angular-ui-router angular-ui

使用 Angular 1.5.5,我尝试使用 Typescript,所以我成功配置了 gulp 任务;现在我尝试使用 SampleService.ts 中的这段代码在 typescript 中提供服务:

module app {
    class SampleService {
        constructor() {
        }

        public toto() :void {
            console.log('test');
        }
    }
    angular.module("app").service("SampleService", [SampleService]);
}

其他地方我有:

angular.module('app',
[ 'ngMaterial',
  'ngAnimate',
 ....

为了声明路由:

$stateProvider
    .state('myapp', {
        url: '',
        controller: 'MainController as vm',
        templateUrl: 'app/views/main.html',
        abstract: true
    })
    .state('myapp.search', {
        url: '/',
        controller: 'SearchController as vm',
        templateUrl: 'app/views/partials/search.html'
    })

没有这个服务声明,一切正常。现在以这种方式声明 SampleService,我得到:

Error: [ng:areq] Argument 'MainController' is not a function, got undefined
http://errors.angularjs.org/1.5.5/ng/areq?p0=MainController&p1=not%20a%20function%2C%20got%20undefined
minErr/<@http://localhost:3000/bower_components/angular/angular.js:68:12
assertArg@http://localhost:3000/bower_components/angular/angular.js:1880:11

即使没有注入(inject)服务,它似乎也会破坏我的应用程序。知道我做错了什么吗?

最佳答案

有一个working plunker 只需像使用服务一样注册 Controller :

module app {
    class SampleService {
        constructor() {
        }

        public toto() :void {
            console.log('test');
        }
    }
    angular.module("app").service("SampleService", [SampleService]);

    class MainController  {

        static $inject = ["$scope", "SampleService"];
        constructor(
            protected $scope, 
            protected SampleService: SampleService) {

            this.init();
        }

        public init() :void {
            this.SampleService.toto();
        }
    }
    angular.module("app").controller("MainController", MainController);
}

并按原样(只是我更喜欢一些 url,其他则为空字符串)

.state('myapp', {
    url: '/myapp',
    controller: 'MainController as vm',
    templateUrl: 'app/views/main.html',
    abstract: true
})
.state('myapp.search', {
    url: '/search',
    controller: 'SearchController as vm',
    templateUrl: 'app/views/partials/search.html'
})

这会起作用:

<a ui-sref="myapp.search">

查一下here in action

关于javascript - 在 Angular 1.5 中使用 Typescript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37478120/

相关文章:

javascript - 如何在 typescript 中捕获数据库插入(运行时)错误并在 chai 中编写合适的测试用例?

typescript - 角度 5 项目中的错误 "ace is not defined"

JavaScript - 为 child 添加跨度?

javascript - JQplot 格式字符串

javascript - 未定义的 Controller AngularJS

javascript - Angularjs select 未将匹配模型标记为已选择

typescript - ionic 2 : Loading component doesn't always dismiss (randomly)

javascript - 使用 javascript 变量值填充特定的 html 元素

javascript 基础 - 时间死区,提升或关闭

javascript - AngularJS 混合来自不同模块的同名 Controller