尝试以下操作:
import { Compiler, COMPILER_OPTIONS, CompilerFactory, NgModule } from '@angular/core';
import { BrowserModule, } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { JitCompilerFactory } from '@angular/platform-browser-dynamic';
export function createCompiler(compilerFactory: CompilerFactory) {
return compilerFactory.createCompiler();
}
@NgModule({
providers: [
{ provide: COMPILER_OPTIONS, useValue: {}, multi: true },
{ provide: CompilerFactory, useClass: JitCompilerFactory, deps: [COMPILER_OPTIONS] },
{ provide: Compiler, useFactory: createCompiler, deps: [CompilerFactory] }
],
imports: [BrowserModule, FormsModule],
declarations: [AppComponent, HelloComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
CODE EXAMPLE
但JitCompiler仍然无法创建依赖项注入树。我
可疑@Injectable将从AOT部件中移除。但我不能做你的
戏法
在上面的代码示例中,没有
装饰师
用于NgModule和Component。所以,这意味着没有
@可注射的
他们也不能注射
providers
。那我们为什么不为
@NgModule模块
和
@组件
@可注射的
装潢师,只写给
服务
?
因为他们有一个装饰器(@NgModule/@Components),
Services
不他们的装饰师足以让Angular知道他们
可注射的
。
CODE EXAMPLE
使用DI。
更新时间:
已创建自定义包装
CustomNgModule
,则,
CustomComponent
和
CustomInjectable
装饰师:
export function CustomComponent(annotation: any) {
return function (target: Function) {
const component = new Component(annotation);
Component(component)(target);
};
}
export function CustomNgModule(annotation: any) {
return function (target: Function) {
const ngModule = new NgModule(annotation);
NgModule(ngModule)(target);
};
}
export function CustomInjectable() {
return function (target: Function) {
const injectable = new Injectable();
Injectable()(target);
};
}
当使用
AOT
标志,Angular CLI看起来像清理捆绑包
来自需要编译的部分代码的本机修饰符
动态。
去你想去的地方
dynamically
使用组件编译模块
在里面
AOT公司
具有
DI
功能,替换本机装饰器
(
NgModule/Injectable...
)定制一个,以保护装饰师
AOT公司
编译模式:
懒惰的单元ts:
@CustomComponent({
selector: 'lazy-component',
template: 'Lazy-loaded component. name: {{name}}.Service
{{service.foo()}}!',
//providers: [SampleService]
})
export class LazyComponent {
name;
constructor(public service: SampleService) {
console.log(service);
console.log(service.foo());
}
}
@CustomNgModule({
declarations: [LazyComponent],
providers: [SampleService]
})
export class LazyModule {
}
应用程序。组成部分ts:
...
ngAfterViewInit() {
this.compiler.compileModuleAndAllComponentsAsync(LazyModule)
.then((factories) => {
const f = factories.componentFactories[0];
const cmpRef = this.vc.createComponent(f);
cmpRef.instance.name = 'dynamic';
});
}
...
CODE EXAMPLE 3