refactor(core): improve an error message when ENVIRONMENT_INITIALIZER is not a multi provider (#46829)

Currently if the `ENVIRONMENT_INITIALIZER` token is not configured with `multi: true` flag, the code fails while trying to iterate over the value. This commit checks whether the `ENVIRONMENT_INITIALIZER` token value type is an array and throws a helpful error message.

PR Close #46829
This commit is contained in:
Andrew Kushnir
2022-07-13 12:31:37 -07:00
committed by Jessica Janiuk
parent 4b452ffd3d
commit d36a9e6bf3
4 changed files with 26 additions and 1 deletions
+2
View File
@@ -47,6 +47,8 @@ export const enum RuntimeErrorCode {
// (undocumented)
INVALID_INJECTION_TOKEN = 204,
// (undocumented)
INVALID_MULTI_PROVIDER = 209,
// (undocumented)
MISSING_GENERATED_DEF = 906,
// (undocumented)
MISSING_INJECTION_CONTEXT = -203,
+8
View File
@@ -272,6 +272,14 @@ export class R3Injector extends EnvironmentInjector {
const previousInjectImplementation = setInjectImplementation(undefined);
try {
const initializers = this.get(ENVIRONMENT_INITIALIZER.multi, EMPTY_ARRAY, InjectFlags.Self);
if (ngDevMode && !Array.isArray(initializers)) {
throw new RuntimeError(
RuntimeErrorCode.INVALID_MULTI_PROVIDER,
'Unexpected type of the `ENVIRONMENT_INITIALIZER` token value ' +
`(expected an array, but got ${typeof initializers}). ` +
'Please check that the `ENVIRONMENT_INITIALIZER` token is configured as a ' +
'`multi: true` provider.');
}
for (const initializer of initializers) {
initializer();
}
+1
View File
@@ -32,6 +32,7 @@ export const enum RuntimeErrorCode {
INJECTOR_ALREADY_DESTROYED = 205,
PROVIDER_IN_WRONG_CONTEXT = 207,
MISSING_INJECTION_TOKEN = 208,
INVALID_MULTI_PROVIDER = 209,
// Template Errors
MULTIPLE_COMPONENTS_MATCH = -300,
@@ -96,7 +96,7 @@ describe('environment injector', () => {
expect(cRef.instance.service).toBeInstanceOf(Service);
});
it('should support the ENVIRONMENT_INITIALIZER muli-token', () => {
it('should support the ENVIRONMENT_INITIALIZER multi-token', () => {
let initialized = false;
const parentEnvInjector = TestBed.inject(EnvironmentInjector);
createEnvironmentInjector(
@@ -110,6 +110,20 @@ describe('environment injector', () => {
expect(initialized).toBeTrue();
});
it('should throw when the ENVIRONMENT_INITIALIZER is not a multi-token', () => {
const parentEnvInjector = TestBed.inject(EnvironmentInjector);
const providers = [{
provide: ENVIRONMENT_INITIALIZER,
useValue: () => {},
}];
expect(() => createEnvironmentInjector(providers, parentEnvInjector))
.toThrowError(
'NG0209: Unexpected type of the `ENVIRONMENT_INITIALIZER` token value ' +
'(expected an array, but got function). ' +
'Please check that the `ENVIRONMENT_INITIALIZER` token is configured as ' +
'a `multi: true` provider.');
});
it('should adopt environment-scoped providers', () => {
const parentEnvInjector = TestBed.inject(EnvironmentInjector);
const injector = createEnvironmentInjector([], parentEnvInjector);