AngularJS Filter with TypeScript and injection

后端 未结 4 1063
没有蜡笔的小新
没有蜡笔的小新 2021-01-12 15:26

Can somebody provide me with an example of how I can create an Angular Filter in TypeScript that uses dependency injection. At the bottom is what I currently have, which is

4条回答
  •  逝去的感伤
    2021-01-12 15:58

    I had the same problem while writing my own DI system for AngularJs 1.3 & Typescript. To solve this I wrote a decorator that accepts a class that implements the following interface:

    interface IFilter {
        filter(value?: any, ...args): any;
    }
    

    and it registers the filter with the following code:

    var filterFactory = (...args) => {
            var filterObject = new target(...args);
            if (typeof filterObject.filter === 'function') {
                return filterObject.filter.bind(filterObject);
            }
            console.warn('Invalid filter: filter() method not found for:', filterName)
            return function() { }; //dummy filter, so it won't break everything
        };
    
    var constructorArray: Array = injector.resolveParamNames(target);
        app.filter(filterName, constructorArray.concat(filterFactory));
    

    My library uses a custom version of the TypeScript compiler, which is able to emit interface metadata that is used by injector.resolveParamNames to build the classic constructor array like this one: ['$q', '$timeout', FilterFactory]

    You can find my project here, and a sample of filter here

提交回复
热议问题