Skip to content

Commit

Permalink
refactor(cdk/private): avoid circular dependency errors in style loader
Browse files Browse the repository at this point in the history
Reworks the style loader to avoid errors if it gets invoked too early.
  • Loading branch information
crisbeto committed Aug 25, 2024
1 parent ad18e6d commit b1731b3
Showing 1 changed file with 10 additions and 6 deletions.
16 changes: 10 additions & 6 deletions src/cdk/private/style-loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
EnvironmentInjector,
inject,
Injectable,
Injector,
Type,
} from '@angular/core';

Expand All @@ -34,25 +35,28 @@ const appsWithLoaders = new WeakMap<
*/
@Injectable({providedIn: 'root'})
export class _CdkPrivateStyleLoader {
private _appRef = inject(ApplicationRef);
private _appRef: ApplicationRef | undefined;
private _injector = inject(Injector);
private _environmentInjector = inject(EnvironmentInjector);

/**
* Loads a set of styles.
* @param loader Component which will be instantiated to load the styles.
*/
load(loader: Type<unknown>): void {
let data = appsWithLoaders.get(this._appRef);
// Resolve the app ref lazily to avoid circular dependency errors if this is called too early.
const appRef = (this._appRef = this._appRef || this._injector.get(ApplicationRef));
let data = appsWithLoaders.get(appRef);

// If we haven't loaded for this app before, we have to initialize it.
if (!data) {
data = {loaders: new Set(), refs: []};
appsWithLoaders.set(this._appRef, data);
appsWithLoaders.set(appRef, data);

// When the app is destroyed, we need to clean up all the related loaders.
this._appRef.onDestroy(() => {
appsWithLoaders.get(this._appRef)?.refs.forEach(ref => ref.destroy());
appsWithLoaders.delete(this._appRef);
appRef.onDestroy(() => {
appsWithLoaders.get(appRef)?.refs.forEach(ref => ref.destroy());
appsWithLoaders.delete(appRef);
});
}

Expand Down

0 comments on commit b1731b3

Please sign in to comment.