Привет Я новичок в angular2 и машинописном тексте. Я загружаю компоненты динамически, и мне было интересно, есть ли способ объявить мои компоненты с помощью службы в «объявлениях» модуля и «entryComponents».Загрузить NgModule entryComponents динамически используя сервис
Использование машинопись, я могу добиться этого, выполнив следующие действия:
import { ComponentLoaderService } from './../../services/component-loader.service';
let componentsToLoad = ComponentLoaderService.getComponents();
@NgModule({
declarations: [ componentsToLoad ],
entryComponents: [ componentsToLoad ],
})
export class testModule {}
Это на самом деле работает, но только если я составил и сервер запущен первый.
Если я пытаюсь перекомпилировать и запустить его, я получаю эту постоянную ошибку:.
«Обнаружена ошибка разрешения значения символов статически вызовы функций не поддерживаются Подумайте о замене функции или лямбды со ссылкой на экспортируемый. function, "
Моя другая мысль была, есть способ поместить загрузку компонентов в" export class testModule {} "часть, чтобы заполнить массив, а затем передать его NgModule?
Из моего текущего теста это не сработает, но я все еще новичок в этом, поэтому я могу что-то упустить.
Надеюсь, кто-то может помочь. Спасибо!
Вот код, который создает ошибку компиляции:
Я просто нг новый тест-приложение.
Затем в папке тестового приложения я установил npm.
Я создал /src/app/services/components-loader.service.ts.
import { Injectable } from '@angular/core';
import { ViewContainerRef, ViewChild, ComponentFactoryResolver } from '@angular/core';
@Injectable()
export class ComponentLoaderService {
constructor(private componentFactoryResolver: ComponentFactoryResolver){}
static getComponents(components: any[]): any[] {
var tmp = Array();
for (var i = 0; i < components.length; ++i){
if (components[i].key == 0){
tmp.push(components[i].component);
}
}
return tmp;
}
load(container: ViewContainerRef, components: any[]): void {
// clear
container.clear();
for (var i = 0; i < components.length; ++i){
if (components[i].key == 0 || components[i].key == 'site'){
const childComponent = this.componentFactoryResolver.resolveComponentFactory(components[i].component);
// at this point we want the "child" component to be rendered into the app.component:
container.createComponent(childComponent);
}
}
}
}
Я создал файл /src/app/components.ts.
import { TestComponent } from './test.component';
export const mainComponents = [
{ key: 0, component: TestComponent },
];
Я создал файл /src/app/test.component.ts.
import { Component } from '@angular/core';
@Component({
template: `test`,
})
export class TestComponent {}
Я изменил /src/app/app.module.ts, чтобы выглядеть так.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { mainComponents } from './components';
import { ComponentLoaderService } from './services/components-loader.service';
let componentsToLoad = ComponentLoaderService.getComponents(mainComponents);
@NgModule({
declarations: [
AppComponent,
componentsToLoad
],
imports: [
BrowserModule,
FormsModule,
HttpModule
],
providers: [],
bootstrap: [AppComponent],
entryComponents: [ componentsToLoad ],
})
export class AppModule { }
Когда я компилирую с помощью нг служить, я получаю эту ошибку:
10% building modules 2/2 modules 0 activeError: Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function, resolving symbol AppModule in D:/angularjs/test-app/src/app/app.module.ts, resolving symbol AppModule in D:/angularjs/test-app/src/app/app.module.ts
Отметьте этот https://github.com/angular/angular-cli/issues/3368#issuecomment-265232700 – yurzui
Также проверьте это https://medium.com/@isaacplmann/making-your-angular-2- библиотека-статический анализируемая-для-АОТ-e1c6f3ebedd5 #.wr4sw2laz – yurzui