Upgrade AngularJS ServiceProvider which provides an interface

224 views Asked by At

I'm trying to upgrade AngularJS service provider (TranslateProvider) which return an instance of an interface from it's $get function.

The problem is that in the Angular provider object (translateProvider) the provide field should be Translate but it cannot be used because TypeScript interfaces are for compile-time only. This is the error I get:

TS2693: 'Translate' only refers to a type, but is being used as a value here.

This is the gist of the source code:

export class TranslateProvider implements ng.IServiceProvider {

    public $get() {

        const service: Translate = <Translate> function translate(key: string, parameters: Dictionary<StringLike>): string {

        return service;
    }
}

export interface Translate {
    (translationKey: string, parameters?: Dictionary<StringLike>): string;
}

export function translateFactory(i: any) {
    return i.get('translate');
}

export const translateProvider = {
    provide: TranslateProvider,
    useFactory: translateFactory,
    deps: ['$injector']
};

@NgModule({
    imports: [
        BrowserModule,
        UpgradeModule,
    ],
    declarations: [
    ],
    providers: [
        translateProvider,
    ]
})
1

There are 1 answers

0
Ido Ran On

I've found in Angular docs the explanation about Injection Tokens.

Somewhere in the code (usually in the file where the interface is defined) you need to add

export const TRANSLATE_TOKEN = new InjectionToken<Translate>('Translate');

This token can be used later to ask the injector for this service.

The upgrade registration now looks like this:

export const translateProvider = {
    provide: TRANSLATE_TOKEN,
    useFactory: translateFactory,
    deps: ['$injector']
};

And finally the ctor of the component that will use this dependency looks like this:

constructor(@Inject(TRANSLATE_TOKEN) private translate: Translate) {
}