From d31dc7b2b3989d78c1b9c57818ed2a435fe9e23c Mon Sep 17 00:00:00 2001 From: Georgios Kalpakas Date: Thu, 20 Jul 2017 19:06:13 +0300 Subject: [PATCH] fix(upgrade): throw error if trying to get injector before setting (#18209) Previously, `undefined` would be returned. This change makes it easier to identify incorrect uses/bugs. (Discussed in https://github.com/angular/angular/pull/18213#issuecomment-316191308.) --- packages/upgrade/src/static/angular1_providers.ts | 4 ++++ packages/upgrade/test/static/angular1_providers_spec.ts | 8 ++++++-- 2 files changed, 10 insertions(+), 2 deletions(-) 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 }); });