栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用具有构造函数参数的TypeScript类定义AngularJS工厂

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用具有构造函数参数的TypeScript类定义AngularJS工厂

至少有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。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/415615.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号