我想编写一个在构造函数中获取“prefix”参数的TypeScript类,该类也需要访问LogService注入。
使用简单的JavaScript,你应该这样做:
angular.module('myModule',[]).factory('LogWithPrefixFactory',['LogService',function(LogService) {
var LogWithPrefixFactory = function(prefix) {
this.prefix = prefix;
}
LogWithPrefixFactory.prototype.log = function(txt) {
// we have access to the injected LogService
LogService.log(this.prefix,txt);
}
return LogWithPrefixFactory;
}]);
所以当你把这个工厂注入一个控制器时,你可以这样启动很多次(不需要注入LogService):
angular.module('myModule').controller('Ctrl',function(LogWithPrefixFactory) {
var foo = new LogWithPrefixFactory("My PREFIX");
var foo = new LogWithPrefixFactory("My OTHER PREFIX");
}
您将如何在TypeScript类中定义此工厂?
TypeScript类不能在函数内定义…
这个类应该可以访问LogService,但是它不能在其中一个注入中获得。
至少有2个选项。
第一个选项是让LogWithPrefixFactory提供返回前缀记录器的getInstance方法。
module services {
class LogService {
$window: any;
constructor($window: any) {
this.$window = $window;
}
log(prefix: string,txt: string) {
this.$window.alert(prefix + ' :: ' + txt);
}
}
angular.module('services').service('LogService',['$window',LogService]);
export interface ILog {
log: (txt) => void;
}
export class LogWithPrefixFactory {
logService: LogService;
constructor(logService: LogService) {
this.logService = logService;
}
getInstance(prefix: string): ILog {
return {
log: (txt: string) => this.logService.log(prefix,txt);
}
}
}
angular.module('services').service('LogWithPrefixFactory',services.LogWithPrefixFactory]);
}
哪些可以在控制器中使用,如:
this.log1 = logWithPrefixFactory.getInstance("prefix1");
this.log2 = logWithPrefixFactory.getInstance("prefix2");
完成广场here。
第二个选项(类似于另一个答案),给Angular另一个函数用作一个构造函数,它可以手动处理LogService构造函数注入(个人而言,我不喜欢static)。
angular.module('services').service('LogWithPrefixFactory',function(logService) {
return function LogWithPrefixFactory(prefix) {
return new LogWithPrefix(prefix,logService);
};
}]);
哪些可以在控制器中使用,如:
this.log1 = new LogWithPrefixFactory("prefix1");
this.log2 = new LogWithPrefixFactory("prefix2");
甚至:
this.log1 = LogWithPrefixFactory("prefix1");
this.log2 = LogWithPrefixFactory("prefix2");
LogWithPrefixFactory注入到控制器中,但它不是TypeScript类构造函数,它是在通过LogService“手动”注入之后返回该类的实际实例的中间函数。
完成广场here。
注意:这些plunkers在浏览器上同步编译typescript。我已经在Chrome上测试过了。不保证他们会工作。最后,我手动添加了一小部分angular.d.ts。完整文件非常大,我的代理不允许大型POST。