【问题标题】:Angular 6: Not able to inject a service in dynamic component using JIT compilationAngular 6:无法使用 JIT 编译在动态组件中注入服务
【发布时间】:2018-10-26 17:27:48
【问题描述】:

我正在尝试在我正在创建的动态组件中注入服务,但是当我尝试注入服务时出现错误。我能够将服务注入到使用 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);
    });
}

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

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

【问题讨论】:

  • 您是否将ApplicantSvc 添加到您的模块中,例如app.module.js?
  • 我已经在 app.module 中添加了它,它在 AOT 编译的其他组件中运行良好。只遇到 JIT 编译组件的问题。

标签: javascript angular typescript


【解决方案1】:

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

  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̶)̶;̶
      ????.??????.????????.?????????????? = ????.????????????????        
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-06
    • 2022-12-19
    • 1970-01-01
    • 2019-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多