Skip to content

Commit 4e10a74

Browse files
pkozlowski-opensourcedylhunn
authored andcommitted
fix(core): imply @optional flag when a default value is provided (#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 #47109 PR Close #47242
1 parent bd66f49 commit 4e10a74

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

packages/core/src/render3/di.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -334,7 +334,7 @@ export function injectAttributeImpl(tNode: TNode, attrNameToInject: string): str
334334

335335
function notFoundValueOrThrow<T>(
336336
notFoundValue: T|null, token: ProviderToken<T>, flags: InjectFlags): T|null {
337-
if (flags & InjectFlags.Optional) {
337+
if ((flags & InjectFlags.Optional) || notFoundValue !== undefined) {
338338
return notFoundValue;
339339
} else {
340340
throwProviderNotFoundError(token, 'NodeInjector');
@@ -352,7 +352,7 @@ function notFoundValueOrThrow<T>(
352352
*/
353353
function lookupTokenUsingModuleInjector<T>(
354354
lView: LView, token: ProviderToken<T>, flags: InjectFlags, notFoundValue?: any): T|null {
355-
if (flags & InjectFlags.Optional && notFoundValue === undefined) {
355+
if ((flags & InjectFlags.Optional) && notFoundValue === undefined) {
356356
// This must be set or the NullInjector will throw for optional deps
357357
notFoundValue = null;
358358
}

packages/core/test/acceptance/di_spec.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1025,6 +1025,24 @@ describe('di', () => {
10251025
const dirC = fixture.componentInstance.dirC;
10261026
expect(dirC.dirB).toBeNull();
10271027
});
1028+
1029+
it('should imply @Optional in presence of a default value', () => {
1030+
const NON_EXISTING_PROVIDER = new InjectionToken<string>('non-existing');
1031+
1032+
@Component({template: ''})
1033+
class MyComp {
1034+
value: string|undefined;
1035+
constructor(injector: Injector) {
1036+
this.value = injector.get(NON_EXISTING_PROVIDER, 'default', InjectFlags.Host);
1037+
}
1038+
}
1039+
1040+
const injector = Injector.create({providers: []});
1041+
expect(injector.get(NON_EXISTING_PROVIDER, 'default', InjectFlags.Host)).toBe('default');
1042+
1043+
const fixture = TestBed.createComponent(MyComp);
1044+
expect(fixture.componentInstance.value).toBe('default');
1045+
});
10281046
});
10291047

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

0 commit comments

Comments
 (0)