5

我正在尝试使用 angular2编译器动态插入一个组件,只要所有代码都在默认模块中,它就可以正常工作。

但是如果尝试将组件放入它自己的功能模块中,它就会中断。注入的编译器实例(ModuleBoundCompiler)绑定到默认模块而不是功能之一,我无法在编译器调用中覆盖该模块,因为由于循环依赖(功能模块导出组件),我无法获得对它的引用, 组件需要引用功能模块)。

知道这是一个错误还是我做错了什么?

默认模块:

import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';

import {AppComponent} from './app.component';

@NgModule({
    imports: [BrowserModule, FeatureModule],
    declarations: [AppComponent],
    bootstrap: [AppComponent]
})
export class AppModule { }

应用组件:

import {Component} from "@angular/core";

@Component({
    selector: "my-app",
    template: `
        <h1>Angular2 RC5 Test</h1>
        <feature-component></feature-component>
    `
})
export class AppComponent { }

功能模块

import { NgModule }     from "@angular/core";
import { CommonModule } from "@angular/common";
import { FormsModule }  from "@angular/forms";

import { FeatureComponent }  from "./feature.component";
import { FeatureService }    from "./feature.service";


@NgModule({
    imports: [CommonModule, FormsModule],
    declarations: [FeatureComponent],
    exports: [FeatureComponent],
    providers: [FeatureService]
})
export class FeatureModule { }

特征组件

import {Component, Compiler, ComponentFactory} from "@angular/core";

import {FeatureService} from "./feature.service";

// import {FeatureModule} from "./feature.module"; // produces error if referenced due to circular dependency


@Component({
    selector: "feature-component",
    template: "<div>Feature Component</div>"
})
export class FeatureComponent {

    constructor(private _service: FeatureService, private _compiler: Compiler) {
        // compiler currently belongs to AppModule (should be FeatureModule)
        console.log((<any>this._compiler)._ngModule); // outputs function AppModule() { }
    }

    public createComponent(component: any): void {
        this._compiler.compileComponentAsync(component /* , could override module here, but can't get reference */)
            .then((factory: ComponentFactory<any>) => {
                 // ...
            });
    }
}
4

0 回答 0