File tree Expand file tree Collapse file tree 2 files changed +20
-2
lines changed
Expand file tree Collapse file tree 2 files changed +20
-2
lines changed Original file line number Diff line number Diff line change @@ -334,7 +334,7 @@ export function injectAttributeImpl(tNode: TNode, attrNameToInject: string): str
334334
335335function 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 */
353353function 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 }
Original file line number Diff line number Diff 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' , ( ) => {
You can’t perform that action at this time.
0 commit comments