我已经编写了一个 Angular 提供程序,需要将 $injector 服务注入(inject)到 $get 函数中,但我不知道如何用 typescript 编写它并使其缩小安全。就像是 静态 $ 注入(inject)器 = ['']; 适用于服务和 Controller 的符号。
typescript :
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;
}];
最佳答案
我想我明白了。在更仔细地阅读 $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'];
关于angularjs - 使用 typescript 缩小编写的 Angular 提供者安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23884913/