简体   繁体   中英

No provider when compileModuleAndAllComponentsAsync() angular2 - 2.0 final version

I have a little method that create a component using Compiler class ('@angular/core') and compileModuleAndAllComponentsAsync() method. When I create the component, have the follow error

No provider for NameService!".

I know what is this error, but the module that I try compile has this provider:

@NgModule({
  imports: [CommonModule, RouterModule, FormsModule],
  declarations: [MyComponent],
  providers: [NameService]
})
export class MyModule {}

Therefore, How I can inject the provider NameService and others providers on the component being created?

this.compiler.compileModuleAndAllComponentsAsync(this._createDynamicComponent())
.then(factory => {
    const compFactory = factory.componentFactories.find((x: any) => x.componentType === this.instanceComponent());
    const cmpRef = this.vcRef.createComponent(compFactory);

    this.addToInstance(cmpRef, (cmpRef) => {
        cmpRef.destroy();
    });
});

After hours looking to code, I found that the problem is because the Component not have provider:[NameService] . I inserted the provider and all worked correctly.

I took long time to discovery this because the component was working normally, only when I tried dynamically create it, it's that the problem happened.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM