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 memberXEnumToStringFilter
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 ?
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 )
There are two things going on here that I will try to address separately.
The closest you can get to typing this would be:
private xEnumToStringFilter: () => string
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With