I created a simple angular standalone component that uses an injection token for configuration:
export const PERSON_DEFAULT_OPTIONS = new InjectionToken<IPersonDefaults>('...')
export interface IPersonDefaults { ... }
export const providePersonDefaultOptions = (options: IPersonDefaults): Provider => ({
provide: PERSON_DEFAULT_OPTIONS,
useValue: options
})
@Component({...})
export class StandaloneComponent {
readonly #config = inject(PERSON_DEFAULT_OPTIONS, {optional: true})
}
In my main.ts I then just call providePersonDefaultOptions() with my values and everything works great.
Now I've taken that token/interface/component and put it into an npm library. When I try and run the app again, it gives me the following error:
Error: NG0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with
EnvironmentInjector#runInContext
I'm not understanding why that code doesn't work as an npm library, since it's still a field initializer where it's being set.
This error may happen because of
1: 2 @angular/core ending up in the bundled application
My problem
I had 3 libraries
a,bandc.aandbwhere both importingc, butaused a different version thanb. one were under angular 14, the other on angular 16.Which made it use 2 different
@angular/coreSolution
I've updated every version of my library to use exactly the same version.
2: Old
estargetIf you're migrating to angular v16, you may need to change the target to
ES2022