From ccbda9de658cd685d947dfc2ac85664a09efb11a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mi=C5=A1ko=20Hevery?= Date: Thu, 14 Jun 2018 10:36:20 -0700 Subject: [PATCH] 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 --- packages/core/src/view/ng_module.ts | 2 ++ packages/core/test/view/ng_module_spec.ts | 12 ++++++++---- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/packages/core/src/view/ng_module.ts b/packages/core/src/view/ng_module.ts index 9e6bd20305..15496ce80f 100644 --- a/packages/core/src/view/ng_module.ts +++ b/packages/core/src/view/ng_module.ts @@ -118,6 +118,8 @@ export function resolveNgModuleDep( return ( data._providers[index] = _createProviderInstance(data, data._def.providersByKey[depDef.tokenKey])); + } else if (depDef.flags & DepFlags.Self) { + return notFoundValue; } return data._parent.get(depDef.token, notFoundValue); } finally { diff --git a/packages/core/test/view/ng_module_spec.ts b/packages/core/test/view/ng_module_spec.ts index 6e3c1fa9a1..3d569c844b 100644 --- a/packages/core/test/view/ng_module_spec.ts +++ b/packages/core/test/view/ng_module_spec.ts @@ -80,11 +80,14 @@ class FromChildWithOptionalDep { } 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 = defineInjectable({ factory: () => new FromChildWithSkipSelfDep( inject(ChildDep, InjectFlags.SkipSelf|InjectFlags.Optional), - inject(Bar, InjectFlags.Self|InjectFlags.Optional)), + inject(ChildDep, InjectFlags.Self), + inject(Bar, InjectFlags.Self|InjectFlags.Optional), ), providedIn: MyChildModule, }); } @@ -162,8 +165,9 @@ describe('NgModuleRef_ injector', () => { it('injects skip-self and self deps across injectors properly', () => { const instance = childRef.injector.get(FromChildWithSkipSelfDep); expect(instance instanceof FromChildWithSkipSelfDep).toBeTruthy(); - expect(instance.depFromParent).toBeNull(); - expect(instance.depFromChild instanceof Bar).toBeTruthy(); + expect(instance.skipSelfChildDep).toBeNull(); + expect(instance.selfChildDep instanceof ChildDep).toBeTruthy(); + expect(instance.optionalSelfBar).toBeNull(); }); it('does not inject something not scoped to the module',