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.)
This commit is contained in:
Georgios Kalpakas 2017-07-20 19:06:13 +03:00 committed by Miško Hevery
parent 4cd4f7a208
commit d31dc7b2b3
2 changed files with 10 additions and 2 deletions

View File

@ -17,6 +17,10 @@ export function setTempInjectorRef(injector: angular.IInjectorService) {
tempInjectorRef = injector; tempInjectorRef = injector;
} }
export function injectorFactory() { export function injectorFactory() {
if (!tempInjectorRef) {
throw new Error('Trying to get the AngularJS injector before it being set.');
}
const injector: angular.IInjectorService|null = tempInjectorRef; const injector: angular.IInjectorService|null = tempInjectorRef;
tempInjectorRef = null; // clear the value to prevent memory leaks tempInjectorRef = null; // clear the value to prevent memory leaks
return injector; return injector;

View File

@ -28,12 +28,16 @@ export function main() {
expect(injector).toBe(mockInjector); 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)', () => { it('should unset the injector after the first call (to prevent memory leaks)', () => {
const mockInjector = {get: () => {}, has: () => false}; const mockInjector = {get: () => {}, has: () => false};
setTempInjectorRef(mockInjector); setTempInjectorRef(mockInjector);
injectorFactory(); injectorFactory();
const injector = injectorFactory(); expect(injectorFactory).toThrowError(); // ...because it has been unset
expect(injector).toBe(null);
}); });
}); });