繁体   English   中英

将Typescript用于Angular 1.5

[英]Use Typescript into Angular 1.5

使用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

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

有一个工作的plunker只需注册控制器,就像你使用服务一样:

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);
}

和状态(只是我更喜欢一些网址,其他字符串为空)

.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">

在这里检查它

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM