diff --git a/packages/upgrade/src/static/angular1_providers.ts b/packages/upgrade/src/static/angular1_providers.ts index 46cc052a8d..36c8187cae 100644 --- a/packages/upgrade/src/static/angular1_providers.ts +++ b/packages/upgrade/src/static/angular1_providers.ts @@ -17,6 +17,10 @@ export function setTempInjectorRef(injector: angular.IInjectorService) { tempInjectorRef = injector; } export function injectorFactory() { + if (!tempInjectorRef) { + throw new Error('Trying to get the AngularJS injector before it being set.'); + } + const injector: angular.IInjectorService|null = tempInjectorRef; tempInjectorRef = null; // clear the value to prevent memory leaks return injector; diff --git a/packages/upgrade/test/static/angular1_providers_spec.ts b/packages/upgrade/test/static/angular1_providers_spec.ts index 94ac3068eb..85c3d98d9e 100644 --- a/packages/upgrade/test/static/angular1_providers_spec.ts +++ b/packages/upgrade/test/static/angular1_providers_spec.ts @@ -28,12 +28,16 @@ export function main() { expect(injector).toBe(mockInjector); }); + it('should throw if the injector value has not been set yet', () => { + const mockInjector = {get: () => {}, has: () => false}; + expect(injectorFactory).toThrowError(); + }); + it('should unset the injector after the first call (to prevent memory leaks)', () => { const mockInjector = {get: () => {}, has: () => false}; setTempInjectorRef(mockInjector); injectorFactory(); - const injector = injectorFactory(); - expect(injector).toBe(null); + expect(injectorFactory).toThrowError(); // ...because it has been unset }); });