OpaqueTokens - why do they require @Inject(token) instead of being typed

32 Views Asked by At

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 }
    ],
    ...
});
0

There are 0 best solutions below