我已经编写了一个角度提供程序,需要在$ get函数中注入$ injector服务,但我不知道如何在打字稿中写这个并使其缩小安全性。就像是 static $ injector = ['']; 适用于服务和控制器的符号。
打字稿:
export class ApiProvider implements IApiProvider {
private baseRoute: string = '';
private endpoints: { [name: string]: IApiEndPointConfig };
static $inject = ['$injector']; //THIS DOES NOT WORK FOR PROVIDERS
constructor() {
this.baseRoute = '';
this.endpoints = {};
}
// MORE CODE
$get = ($injector: ng.auto.IInjectorService): { [name: string]: ApiEndpoint } => {
var api: { [name: string]: ApiEndpoint } = {};
var self:ApiProvider = this;
angular.forEach(this.endpoints, (endpointConfig, name) => {
api[name] = $injector.instantiate(ApiEndpoint, {
baseRoute: self.baseRoute,
endpointConfig: endpointConfig
});
});
return api;
};
}
为$ get函数生成的javascript是:
this.$get = function ($injector) {
var api = {};
var self = _this;
angular.forEach(_this.endpoints, function (endpointConfig, name) {
api[name] = $injector.instantiate(Model.ApiEndpoint, {
baseRoute: self.baseRoute,
endpointConfig: endpointConfig
});
});
return api;
};
我想要的是:
this.$get = ['$injector', function ($injector) {
var api = {};
var self = _this;
angular.forEach(_this.endpoints, function (endpointConfig, name) {
api[name] = $injector.instantiate(Model.ApiEndpoint, {
baseRoute: self.baseRoute,
endpointConfig: endpointConfig
});
});
return api;
}];
答案 0 :(得分:16)
我想我明白了。在更仔细地阅读$ injector文档之后,我发现$ inject字符串数组表示法可用于任何函数。因此我做了类似的事情:
constructor(){
this.$get.$inject = ['$injector'];
}
$get = ($injector: ng.auto.IInjectorService): { [name: string]: ApiEndpoint } => {
//using $injector
};
产生:
this.$get = function ($injector) {
//using $injector
};
this.$get.$inject = ['$injector'];