Я переписываю библиотеку из NG4 -> NG6 (используя angular-cli 6). Эта библиотека изменяет динамические и угловые компоненты, поэтому я использую ComponentFactoryResolver
, и здесь я застрял. Когда я добавляю ComponentFactoryResolver
в конструктор:
constructor(
private componentFactoryResolver: ComponentFactoryResolver
) {}
и сборка lib (с успехом) в целевом приложении (я добавляю lib в package.json из локального файла) У меня есть эта ошибка:
StaticInjectorError(AppModule)[MyLibComponent-> ComponentFactoryResolver]:
StaticInjectorError(Platform: core)[MyLibComponent-> ComponentFactoryResolver]:
NullInjectorError: No provider for ComponentFactoryResolver!
at NullInjector.push../node_modules/@angular/core/fesm5/core.js.NullInjector.get (core.js:979)
at resolveToken (core.js:1232)
at tryResolveToken (core.js:1182)
at StaticInjector.push../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (core.js:1077)
at resolveToken (core.js:1232)
at tryResolveToken (core.js:1182)
at StaticInjector.push../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (core.js:1077)
at resolveNgModuleDep (core.js:9238)
at NgModuleRef_.push../node_modules/@angular/core/fesm5/core.js.NgModuleRef_.get (core.js:9919)
Без ComponentFactoryResolver
все работает правильно
Полный компонент:
import { Component, ComponentFactoryResolver, AfterContentInit, ViewChild, Inject, Input, InjectionToken } from '@angular/core';
import { AbHostDirective } from './../directives/ab-host.directive';
export const AB_COMPONENTS = new InjectionToken('AB_COMPONENTS');
@Component({
selector: 'lib-ab',
template: `<ng-template lib-ab-host></ng-template>`,
styles: []
})
export class MyLibComponent implements AfterContentInit {
@ViewChild(AbHostDirective) abHost: AbHostDirective;
@Input() globalConfiguration: any;
@Input() domain = '';
constructor(
@Inject(AB_COMPONENTS) private $configuredComponents: any,
private componentFactoryResolver: ComponentFactoryResolver
) {}
ngAfterContentInit() {
const currentConfiguration = this.$configuredComponents[this.domain];
if (!currentConfiguration) {
console.error('No component for: ', + this.domain);
return;
}
const randomIndex = Math.floor(Math.random() * currentConfiguration.length);
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(currentConfiguration[randomIndex]);
const viewContainerRef = this.abHost.viewContainerRef;
viewContainerRef.clear();
const componentRef = viewContainerRef.createComponent(componentFactory);
const instance = <any>componentRef.instance;
instance.globalConfiguration = this.globalConfiguration;
}
}