Skip to content

Injector.get throws when default value is provided (when inject flags are present) #47109

@CSchulz

Description

@CSchulz

Which @angular/* package(s) are the source of the bug?

core

Is this a regression?

Yes

Description

The injector.get documentation explains the usage of the notFoundValue and how it is handled.

/**
* Retrieves an instance from the injector based on the provided token.
* @returns The instance from the injector if defined, otherwise the `notFoundValue`.
* @throws When the `notFoundValue` is `undefined` or `Injector.THROW_IF_NOT_FOUND`.
*/
abstract get<T>(token: ProviderToken<T>, notFoundValue?: T, flags?: InjectFlags): T;

But the implementation requires the usage of InjectorFlags.Optional

function notFoundValueOrThrow<T>(
notFoundValue: T|null, token: ProviderToken<T>, flags: InjectFlags): T|null {
if (flags & InjectFlags.Optional) {
return notFoundValue;
} else {
throwProviderNotFoundError(token, 'NodeInjector');
}
}

Please provide a link to a minimal reproduction of the bug

No response

Please provide the exception or error you saw

Error: NG0201: No provider for NgControl found in NodeInjector. Find more at https://angular.io/errors/NG0201
    at throwProviderNotFoundError (node_modules\@angular\core\fesm2020\core.mjs:254:11)
    at notFoundValueOrThrow (node_modules\@angular\core\fesm2020\core.mjs:3349:9)
    at lookupTokenUsingModuleInjector (node_modules\@angular\core\fesm2020\core.mjs:3384:12)
    at getOrCreateInjectable (node_modules\@angular\core\fesm2020\core.mjs:3486:12)
    at NodeInjector.get (node_modules\@angular\core\fesm2020\core.mjs:3661:16)

Please provide the environment you discovered this bug in (run ng version)

The implementation didn't change on the master branch.

Angular CLI: 13.3.9
Node: 16.14.2
Package Manager: npm 8.5.0
OS: win32 x64

Angular: 13.3.11
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1303.9
@angular-devkit/build-angular   13.3.9
@angular-devkit/core            13.3.9
@angular-devkit/schematics      13.3.9
@angular/cli                    13.3.9
@schematics/angular             13.3.9
ng-packagr                      13.3.1
rxjs                            7.5.6
typescript                      4.6.4

Anything else?

No response

Metadata

Metadata

Labels

P3An issue that is relevant to core functions, but does not impede progress. Important, but not urgentarea: coreIssues related to the framework runtimecore: distate: has PR

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions