我正在尝试使用 angularjs 和 typescript 构建一个 Web 应用程序,但我完全陷入了尝试将服务注入(inject)我的一个 Controller 中的境地。
服务
var mod= angular.module("servicemodul", []);
class Service
{
http: ng.IHttpService;
q: ng.IQService;
private user: User;
static $inject = ["$http", "$q"];
constructor($http: ng.IHttpService, $q:ng.IQService)
{
}
}
mod.service('Service',["$http", "$q", function ($http, $q) {
return new Service($http, $q);
}]);
Controller
angular.module("app", ["servicemodul"])
class MainController
{
scope: ng.IScope;
http: ng.IHttpService;
service: Service;
static $inject = ["$scope", "$http", "Service"];
constructor($scope: ng.IScope, $http: ng.IHttpService, service: Service)
{
this.http = $http;
this.scope = $scope;
this.Service= service;
(<any>this.scope).Main = this;
}
public Init()
{
}
}
加载实际页面时,开发者控制台显示:
Unknown provider: ServicePorvider <- Service
问题一定是在模块中注册服务的部分,我已经尝试过 module.factory() 方法,但它导致了相同的错误。 我还确保所有生成的 js 文件都按正确的顺序加载(服务在 Controller 之前)。
另一个小问题:为服务和 Controller 使用不同的模块是否有意义,或者是否可以将所有内容放入一个模块中(假设整个应用程序很小)
最佳答案
您需要向模块注册 Controller :
var appMod = angular.module("app", ["servicemodul"])
appMod.controller('MainController',MainController);
否则 Controller 将不知道servicemodul
关于javascript - 在 angularjs 中注册服务(使用 typescript ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19251498/