使用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
即使没有注入服务,它似乎也会破坏我的应用程序。我知道我做错了什么?
答案 0 :(得分:3)
有一个working 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">