Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Filter + Typescript

I have a very simple angular filter.

This filter takes in input a member of an enum (called here XEnum) and returns the string which represent the member in the enum :

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}} print Started

{{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 only get a strange error :

module Services {
    "use strict";

    export class ServiceUsingXEnum {

        constructor(
            private xEnumToStringFilter: Filters.XEnumToStringFilter // error here
            ) {
            // some beautiful code ...
        }
    }
}

Module Filters has no exported member XEnumToStringFilter

Even when my autocompletion say it exist !

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

Why can't I use XEnumToStringFilter as a type ?

What is a better way to solve it ?

like image 828
antoinestv Avatar asked Apr 16 '15 14:04

antoinestv


2 Answers

That's because you're using the function as Type Declaration. You either:

1) Change the service's constructor declaration:

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

or

2) Create an Interface and use it interface where you want to use the 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 )

like image 106
Marcelo De Zen Avatar answered Oct 31 '22 07:10

Marcelo De Zen


There are two things going on here that I will try to address separately.

1 - A filter is a function not a type

The closest you can get to typing this would be:

private xEnumToStringFilter: () => string

2 - Improper usage of a filter inside service/controller

In order to use a filter in a service/controller you must inject in the $filter service which you can use to get a reference to your filter via the name it is registered, see the example here

like image 30
Brocco Avatar answered Oct 31 '22 09:10

Brocco