@@ -13,6 +13,7 @@ import {
13
13
EnvironmentInjector ,
14
14
inject ,
15
15
Injectable ,
16
+ Injector ,
16
17
Type ,
17
18
} from '@angular/core' ;
18
19
@@ -34,25 +35,28 @@ const appsWithLoaders = new WeakMap<
34
35
*/
35
36
@Injectable ( { providedIn : 'root' } )
36
37
export class _CdkPrivateStyleLoader {
37
- private _appRef = inject ( ApplicationRef ) ;
38
+ private _appRef : ApplicationRef | undefined ;
39
+ private _injector = inject ( Injector ) ;
38
40
private _environmentInjector = inject ( EnvironmentInjector ) ;
39
41
40
42
/**
41
43
* Loads a set of styles.
42
44
* @param loader Component which will be instantiated to load the styles.
43
45
*/
44
46
load ( loader : Type < unknown > ) : void {
45
- let data = appsWithLoaders . get ( this . _appRef ) ;
47
+ // Resolve the app ref lazily to avoid circular dependency errors if this is called too early.
48
+ const appRef = ( this . _appRef = this . _appRef || this . _injector . get ( ApplicationRef ) ) ;
49
+ let data = appsWithLoaders . get ( appRef ) ;
46
50
47
51
// If we haven't loaded for this app before, we have to initialize it.
48
52
if ( ! data ) {
49
53
data = { loaders : new Set ( ) , refs : [ ] } ;
50
- appsWithLoaders . set ( this . _appRef , data ) ;
54
+ appsWithLoaders . set ( appRef , data ) ;
51
55
52
56
// When the app is destroyed, we need to clean up all the related loaders.
53
- this . _appRef . onDestroy ( ( ) => {
54
- appsWithLoaders . get ( this . _appRef ) ?. refs . forEach ( ref => ref . destroy ( ) ) ;
55
- appsWithLoaders . delete ( this . _appRef ) ;
57
+ appRef . onDestroy ( ( ) => {
58
+ appsWithLoaders . get ( appRef ) ?. refs . forEach ( ref => ref . destroy ( ) ) ;
59
+ appsWithLoaders . delete ( appRef ) ;
56
60
} ) ;
57
61
}
58
62
0 commit comments