Angular Filter + Typescript

I have a very simple angular filter.

This filter takes the input of the enum element (called XEnum here) and returns a string that represents the member in the enumeration:

module Filters { "use strict"; export function XEnumToStringFilter() { return ( input: XEnum ) => { return XEnum[input]; } } } [...] module Model { export enum XEnum{ Started = 0, Stopped = 1 } } [...] app.filter( "xEnumToStringFilter", [Filters.XEnumToStringFilter] ); 

This works very well when I use xEnumToStringFilter in my views:

{{0 | etatTransfertEnumToStringFilter}} {{0 | etatTransfertEnumToStringFilter}} print Started

{{1 | etatTransfertEnumToStringFilter}} {{1 | etatTransfertEnumToStringFilter}} print Stopped

But I want to use this filter in my service:

 app.service( "serviceUsingXEnum", ["xEnumToStringFilter", Services.ServiceUsingXEnum] ); 

But in my service constructor, I get a strange error:

 module Services { "use strict"; export class ServiceUsingXEnum { constructor( private xEnumToStringFilter: Filters.XEnumToStringFilter // error here ) { // some beautiful code ... } } } 

Filters module does not have exported XEnumToStringFilter element

Even when my autocomplete says it exists!

I want to use dependency injection, I could just do Filters.XEnumToStringFilter()(somethingXEnum) , but it's bad!

Why can't I use XEnumToStringFilter as a type?

What is the best way to solve this problem?

+6
source share
2 answers

This is because you use the function as a type declaration. You either:

1) Change the declaration of the service constructor:

constructor(private xEnumToStringFilter: ( enum: XEnum ) => string )

or

2) Create an interface and use its interface in which you want to use a filter:

 module Filters { "use strict"; export interface IXEnumToStringFunction { ( input: XEnum ) => string } export function XEnumToStringFilter() { return ( input: XEnum ) => { return XEnum[input]; } } } 

...

then in the constructor

constructor(private xEnumToStringFilter: Filters.IXEnumToStringFunction )

+4
source

There are two things here that I will try to solve separately.

1 - Filter is a function, not a type

Closest you can type this:

 private xEnumToStringFilter: () => string 

2 - Improper use of the filter inside the service / controller

To use a filter in a service / controller, you must enter $filter in the service, which you can use to get a link to your filter through the name that it is registered in, see the example here

+2
source

Source: https://habr.com/ru/post/985271/


All Articles