gpt4 book ai didi

javascript - Angular 6 : Not able to inject a service in dynamic component using JIT compilation

转载 作者:太空狗 更新时间:2023-10-29 17:40:18 24 4
gpt4 key购买 nike

我正在尝试在我正在创建的动态组件中注入(inject)一个服务,但是当我尝试注入(inject)一个服务时出现错误。我能够在所有其他使用 AOT 的组件中注入(inject)服务,但在我使用 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,然后注入(inject)了动态组件构造函数,但每当我尝试这样做时,我都会收到错误

ERROR Error: Can't resolve all parameters for class_1: (?). ..... ..... at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._loadModules (compiler.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̶)̶;̶
𝘁𝗵𝗶𝘀.𝗰𝗺𝗽𝗥𝗲𝗳.𝗶𝗻𝘀𝘁𝗮𝗻𝗰𝗲.𝗮𝘄𝗲𝘀𝗼𝗺𝗲𝗦𝗲𝗿𝘃𝗶𝗰𝗲 = 𝘁𝗵𝗶𝘀.𝗺𝘆𝗔𝘄𝗲𝘀𝗼𝗺𝗲𝗦𝗲𝗿𝘃𝗶𝗰𝗲
});

关于javascript - Angular 6 : Not able to inject a service in dynamic component using JIT compilation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50374600/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com