Skip to content

Commit

Permalink
fix: prevent invoking destroyed injector (#1500)
Browse files Browse the repository at this point in the history
  • Loading branch information
dhhyi authored Sep 8, 2023
1 parent 2d0bf20 commit 6cabc7d
Showing 1 changed file with 34 additions and 15 deletions.
49 changes: 34 additions & 15 deletions src/app/core/utils/module-loader/module-loader.service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Injectable, InjectionToken, Injector, Type, createNgModule } from '@angular/core';
import { ApplicationRef, Injectable, InjectionToken, Injector, OnDestroy, Type, createNgModule } from '@angular/core';
import { Store, select } from '@ngrx/store';
import { Subject, takeUntil } from 'rxjs';

import { getFeatures } from 'ish-core/store/core/configuration';
import { FeatureToggleService } from 'ish-core/utils/feature-toggle/feature-toggle.service';
Expand All @@ -13,23 +14,41 @@ declare interface LazyModuleType {
export const LAZY_FEATURE_MODULE = new InjectionToken<LazyModuleType>('lazyModule');

@Injectable({ providedIn: 'root' })
export class ModuleLoaderService {
export class ModuleLoaderService implements OnDestroy {
private loadedModules: Type<unknown>[] = [];

constructor(private featureToggleService: FeatureToggleService, private store: Store) {}
private destroy$ = new Subject<void>();

constructor(
private featureToggleService: FeatureToggleService,
private store: Store,
private appRef: ApplicationRef
) {}

init(injector: Injector) {
this.store.pipe(select(getFeatures), whenTruthy()).subscribe(() => {
const lazyModules = injector.get<LazyModuleType[]>(LAZY_FEATURE_MODULE, []);
lazyModules
.filter(mod => this.featureToggleService.enabled(mod.feature))
.forEach(async mod => {
const loaded = await mod.location();
if (!this.loadedModules.includes(loaded)) {
createNgModule(loaded, injector);
this.loadedModules.push(loaded);
}
});
});
this.store
.pipe(
select(getFeatures),
whenTruthy(),
takeUntil(this.appRef.isStable.pipe(whenTruthy())),
takeUntil(this.destroy$)
)
.subscribe(() => {
const lazyModules = injector.get<LazyModuleType[]>(LAZY_FEATURE_MODULE, []);
lazyModules
.filter(mod => this.featureToggleService.enabled(mod.feature))
.forEach(async mod => {
const loaded = await mod.location();
if (!this.loadedModules.includes(loaded)) {
createNgModule(loaded, injector);
this.loadedModules.push(loaded);
}
});
});
}

ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
}

0 comments on commit 6cabc7d

Please sign in to comment.