Angular 6:无法使用 JIT 编译在动态组件中注入服务



我正在尝试在我正在创建的动态组件中注入服务,但是当我尝试注入服务时出现错误。我可以在使用 AOT 的所有其他组件中注入服务,但在使用 JIT 时不能。这是代码。

import { Injectable } from '@angular/core';
@Injectable
export class ApplicantSvc
{
name:string;  
}
private createComponentFromRaw(template: string){
const tmpCmp = Component({ template })(class {
constructor(private app :ApplicantSvc){}
});
// Now, also create a dynamic module.
const tmpModule = NgModule({
declarations: [tmpCmp],
imports: [CommonModule],
providers: [ApplicantSvc],
})(class {});

this.compiler.compileModuleAndAllComponentsAsync(tmpModule)
.then((factories) => {
const f = factories.componentFactories[0];
this.cmpRef = f.create(this.injector, [], null, this.moduleRef);
this.cmpRef.instance.name = 'my-dynamic-component';
this.vc.insert(this.cmpRef.hostView);
});
}

在上面的代码中,我在动态模块中为提供程序添加了 ApplicantSvc,然后注入到动态组件构造函数中,但每当我尝试这样做时,我都会收到错误

错误

错误:无法解析class_1的所有参数:(?(。 ..... .....在 JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._loadModules (编译器.js:22570(

我发现简单地像变量一样传递服务就可以了

this.compiler.compileModuleAndAllComponentsAsync(tmpModule)
.then((factories) => {
const f = factories.componentFactories[0];
this.cmpRef = f.create(this.injector, [], null, this.moduleRef);
this.cmpRef.instance.name = 'my-dynamic-component';
̶t̶h̶i̶s̶.̶v̶c̶.̶i̶n̶s̶e̶r̶t̶(̶t̶h̶i̶s̶.̶c̶m̶p̶R̶e̶f̶.̶h̶o̶s̶t̶V̶i̶e̶w̶)̶;̶
𝘁𝗵𝗶𝘀.𝗰𝗺𝗽𝗥𝗲𝗳.𝗶𝗻𝘀𝘁𝗮𝗻𝗰𝗲.𝗮𝘄𝗲𝘀𝗼𝗺𝗲𝗦𝗲𝗿𝘃𝗶𝗰𝗲 = 𝘁𝗵𝗶𝘀.𝗺𝘆𝗔𝘄𝗲𝘀𝗼𝗺𝗲𝗦𝗲𝗿𝘃𝗶𝗰𝗲        
});

最新更新