如何使用具有构造函数参数的TypeScript类来定义AngularJS工厂
我想编写一个在构造函数中获取“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类中定义此工厂?
至少有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。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- scala – 如何在sbt中所有模块的所有测试之前运行任务
- angularjs – Angular-Strap datepicker的动态放置
- 使用无形scala合并两个不同案例类的字段
- osx – 可以从终端快速搜索/替换多个.txt文件吗?
- scala lazy val:垃圾收集器上的一个好方法吗?
- 【数据结构】堆heap,Trie树,位图Bitmap
- twitter-bootstrap – 如何在Meteor 0.9上安装bootstrap-3?
- scala – 在Slick查询中比较类型映射值
- 添加/删除元素时未更新angularjs ng-repeat列表
- angularjs – 如何重定向在ui路由器解析?