至少有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', ['LogService', services.LogWithPrefixFactory]);}可以在控制器中使用,例如:
this.log1 = logWithPrefixFactory.getInstance("prefix1");this.log2 = logWithPrefixFactory.getInstance("prefix2");在这里完整地塞一下。
第二个选项(类似于另一个答案),为Angular提供了另一个要用作构造函数的函数,该函数手动处理
LogService构造函数注入(个人而言,我不喜欢
static)。
angular.module('services').service('LogWithPrefixFactory', ['LogService', 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。
在这里完整地塞一下。
注意:这些插件会在浏览器上同步编译打字稿。我只在Chrome上测试过。不能保证它们会起作用。最后,我手动添加了一小部分angular.d.ts。完整文件非常大,我的代理服务器不允许大型POST。



