Skip to content

Commit

Permalink
fix(core): imply @optional flag when a default value is provided (ang…
Browse files Browse the repository at this point in the history
…ular#47242)

Unify default value handling across injector and node injector: as long
as a default value is provided it has the same effect as specifying the
@optional() flag.

Fixes angular#47109

PR Close angular#47242
  • Loading branch information
pkozlowski-opensource authored and vyom1611 committed Sep 18, 2022
1 parent 31a0edf commit 282c642
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
4 changes: 2 additions & 2 deletions packages/core/src/render3/di.ts
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,7 @@ export function injectAttributeImpl(tNode: TNode, attrNameToInject: string): str

function notFoundValueOrThrow<T>(
notFoundValue: T|null, token: ProviderToken<T>, flags: InjectFlags): T|null {
if (flags & InjectFlags.Optional) {
if ((flags & InjectFlags.Optional) || notFoundValue !== undefined) {
return notFoundValue;
} else {
throwProviderNotFoundError(token, 'NodeInjector');
Expand All @@ -352,7 +352,7 @@ function notFoundValueOrThrow<T>(
*/
function lookupTokenUsingModuleInjector<T>(
lView: LView, token: ProviderToken<T>, flags: InjectFlags, notFoundValue?: any): T|null {
if (flags & InjectFlags.Optional && notFoundValue === undefined) {
if ((flags & InjectFlags.Optional) && notFoundValue === undefined) {
// This must be set or the NullInjector will throw for optional deps
notFoundValue = null;
}
Expand Down
18 changes: 18 additions & 0 deletions packages/core/test/acceptance/di_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1025,6 +1025,24 @@ describe('di', () => {
const dirC = fixture.componentInstance.dirC;
expect(dirC.dirB).toBeNull();
});

it('should imply @Optional in presence of a default value', () => {
const NON_EXISTING_PROVIDER = new InjectionToken<string>('non-existing');

@Component({template: ''})
class MyComp {
value: string|undefined;
constructor(injector: Injector) {
this.value = injector.get(NON_EXISTING_PROVIDER, 'default', InjectFlags.Host);
}
}

const injector = Injector.create({providers: []});
expect(injector.get(NON_EXISTING_PROVIDER, 'default', InjectFlags.Host)).toBe('default');

const fixture = TestBed.createComponent(MyComp);
expect(fixture.componentInstance.value).toBe('default');
});
});

it('should check only the current node with @Self', () => {
Expand Down

0 comments on commit 282c642

Please sign in to comment.