coalescing-component-factory.resolver.ts 1.89 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
import { ComponentFactory, ComponentFactoryResolver, Injectable, Type } from '@angular/core';

/**
 * This is a hack to enable entry components of lazily-loaded modules to be available outside of the module in which
 * they were declared.
 *
 * From: https://github.com/jonrimmer/angular-coalescing-component-factory-resolver/blob/master/src/app/coalescing-component-factory-resolver.service.ts
 *
 * GitHub issue: https://github.com/angular/angular/issues/14324#issuecomment-481898762
 */
@Injectable({ providedIn: 'root' })
export class CoalescingComponentFactoryResolver extends ComponentFactoryResolver {
  private rootResolve: (component: Type<any>) => ComponentFactory<any>;

  private inCall = false;

  private readonly resolvers = new Map<ComponentFactoryResolver, (component: Type<any>) => ComponentFactory<any>>();

  constructor(private readonly rootResolver: ComponentFactoryResolver) {
    super();
    this.rootResolve = this.rootResolver.resolveComponentFactory;
    this.rootResolver.resolveComponentFactory = this.resolveComponentFactory;
  }

  public registerResolver(resolver: ComponentFactoryResolver): void {
    const original = resolver.resolveComponentFactory;
    this.resolvers.set(resolver, original);
  }

  public resolveComponentFactory = <T>(component: Type<T>): ComponentFactory<T> => {
    // Prevents cyclic calls.
    if (this.inCall) {
      return null;
    }

    this.inCall = true;
    try {
      const result = this.resolveInternal(component);
      return result;
    } finally {
      this.inCall = false;
    }
  };

  private resolveInternal = <T>(component: Type<T>): ComponentFactory<T> => {
    for (const [resolver, fn] of Array.from(this.resolvers.entries())) {
      try {
        const factory = fn.call(resolver, component);
        if (factory) {
          return factory;
        }
      } catch {}
    }

    return this.rootResolve.call(this.rootResolver, component);
  };
}