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