Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(core): imply @Optional flag when a default value is provided #47242

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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