Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了如何使用具有构造函数参数的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类中定义此工厂?
TypeScript类不能在函数内定义…
这个类应该可以访问Logservice,但是它不能在其中一个注入中获得。

至少有2个选项。

一个选项是让LogWithPrefixFactory提供返回前缀记录器的geTinstance方法

@H_150_3@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。

大佬总结

以上是大佬教程为你收集整理的如何使用具有构造函数参数的TypeScript类来定义AngularJS工厂全部内容,希望文章能够帮你解决如何使用具有构造函数参数的TypeScript类来定义AngularJS工厂所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。