fix(core): Injector correctly honors the @Self flag (#24520)

Injector was incorrectly returning instance from parent injector even
when `@Self` was specified.

PR Close #24520
This commit is contained in:
Miško Hevery 2018-06-14 10:36:20 -07:00
parent 27bc7dcb43
commit ccbda9de65
2 changed files with 10 additions and 4 deletions

View File

@ -118,6 +118,8 @@ export function resolveNgModuleDep(
return ( return (
data._providers[index] = data._providers[index] =
_createProviderInstance(data, data._def.providersByKey[depDef.tokenKey])); _createProviderInstance(data, data._def.providersByKey[depDef.tokenKey]));
} else if (depDef.flags & DepFlags.Self) {
return notFoundValue;
} }
return data._parent.get(depDef.token, notFoundValue); return data._parent.get(depDef.token, notFoundValue);
} finally { } finally {

View File

@ -80,11 +80,14 @@ class FromChildWithOptionalDep {
} }
class FromChildWithSkipSelfDep { class FromChildWithSkipSelfDep {
constructor(public depFromParent: ChildDep|null, public depFromChild: Bar|null) {} constructor(
public skipSelfChildDep: ChildDep|null, public selfChildDep: ChildDep|null,
public optionalSelfBar: Bar|null) {}
static ngInjectableDef: InjectableDef<FromChildWithSkipSelfDep> = defineInjectable({ static ngInjectableDef: InjectableDef<FromChildWithSkipSelfDep> = defineInjectable({
factory: () => new FromChildWithSkipSelfDep( factory: () => new FromChildWithSkipSelfDep(
inject(ChildDep, InjectFlags.SkipSelf|InjectFlags.Optional), inject(ChildDep, InjectFlags.SkipSelf|InjectFlags.Optional),
inject(Bar, InjectFlags.Self|InjectFlags.Optional)), inject(ChildDep, InjectFlags.Self),
inject(Bar, InjectFlags.Self|InjectFlags.Optional), ),
providedIn: MyChildModule, providedIn: MyChildModule,
}); });
} }
@ -162,8 +165,9 @@ describe('NgModuleRef_ injector', () => {
it('injects skip-self and self deps across injectors properly', () => { it('injects skip-self and self deps across injectors properly', () => {
const instance = childRef.injector.get(FromChildWithSkipSelfDep); const instance = childRef.injector.get(FromChildWithSkipSelfDep);
expect(instance instanceof FromChildWithSkipSelfDep).toBeTruthy(); expect(instance instanceof FromChildWithSkipSelfDep).toBeTruthy();
expect(instance.depFromParent).toBeNull(); expect(instance.skipSelfChildDep).toBeNull();
expect(instance.depFromChild instanceof Bar).toBeTruthy(); expect(instance.selfChildDep instanceof ChildDep).toBeTruthy();
expect(instance.optionalSelfBar).toBeNull();
}); });
it('does not inject something not scoped to the module', it('does not inject something not scoped to the module',