0

Why do I need to @Inject(...) an OpaqueToken, instead of using it like a type?

Why does this work:

import { AppConstantsToken } from './app.constants.ts';

export class MyApp {
    constructor(@Inject(AppConstantsToken) private config) {
    }
}

And this does not:

import { AppConstantsToken } from './app.constants.ts';

export class MyApp {
    constructor(private config: AppConstantsToken) {
    }
}

When I have the following OpaqueToken declared/provided:

app.constants.ts:

import { OpaqueToken } from '@angular/core';

export const APP_CONSTANTS = {
    apiUri: 'appapi.com'
};

export const AppConstantsToken = new OpaqueToken('APPCONSTANTS');

export function provideAppConstants() {
    return APP_CONSTANTS;
}

app.module.ts:

import { AppConstantsToken, provideAppConstants } from './app.constants.ts';

@NgModule({
    ...,
    providers: [
        { provide AppConstantsToken, useFactory: provideAppConstants }
    ],
    ...
});
Estus Flask
  • 206,104
  • 70
  • 425
  • 565
keldar
  • 6,152
  • 10
  • 52
  • 82
  • What do you mean by "instead of being typed"? I think this might help you understand whatever it is you are not understanding.. http://stackoverflow.com/a/40019237/2587435 – Paul Samsotha Feb 08 '17 at 09:29
  • 1
    `AppConstantsToken` is not a `Type`, it’s a value which means typeScript cannot compile it. – yurzui Feb 08 '17 at 09:33
  • 1
    Take a look at this article https://toddmotto.com/angular-dependency-injection#inject – yurzui Feb 08 '17 at 09:34
  • 1
    The cited answer really covers this. You can't do something like `config: AppConstantsToken` in TS because `config` isn't `AppConstantsToken` type. It is `Object`. – Estus Flask Feb 08 '17 at 09:34
  • I.e.: `private config: AppConstantsToken` - TypeScript complains `Cannot find name 'AppConstantsToken'` – keldar Feb 08 '17 at 09:35
  • Thanks everyone. Question sufficiently answered. – keldar Feb 08 '17 at 09:36

0 Answers0