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:
parent
4cd4f7a208
commit
d31dc7b2b3
|
@ -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;
|
||||
|
|
|
@ -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
|
||||
});
|
||||
});
|
||||
|
||||
|
|
Loading…
Reference in New Issue