How can I define an AngularJS factory using TypeScript class that has constructor parameters

前端 未结 6 846
北恋
北恋 2020-12-30 01:53

I want to write a TypeScript class that gets a \"prefix\" parameter in the constructor, this class also needs access to a LogService inject.

Using plain JavaScript y

6条回答
  •  轮回少年
    2020-12-30 02:19

    You can create a type that allows you to define what the constructor of the factory looks like:

    // Defining the factory
    
    // THIS IS THE IMPORTANT PART!!
    export type SelectorFactory = new (config: any) => Selector;
    
    export class Selector {
    
        constructor(protected config: any, protected $http: ng.IHttpService) {
            // do some stuff
        }
    }
    
    angular.module('app')
        .factory('Selector', ($http: ng.IHttpService) => {
            // This is what the factory looks like to the end user
            return (config: any) => {
                return new Selector(config, $http);
            };
        });
    
    // Using the factory
    export class SampleCtrl {
        constructor(public SelectorFactory: SelectorFactory) {
            let config = { op: 1 };
    
            let selector: Selector = new SelectorFactory(config);
        }
    }
    

提交回复
热议问题