简体   繁体   中英

Angular 2 inject service into dynamic component

I'm creating a multi-step user signup where after each step, the server returns the HTML string of the next form to complete. At each step, I set that HTML as the template of a Form Component that I dynamically created using a CompileService. This works fine and the form looks good, but I can't add any services to that dynamically created form, I keep getting issues like

"Cannot resolve all parameters"

Here is my CompileService

import { Component, ComponentMetadata, ComponentResolver, Injectable, ReflectiveInjector, ViewContainerRef } from '@angular/core';

@Injectable()
export class CompileService {
constructor(private resolver: ComponentResolver) {}

createComponent(metadata: ComponentMetadata, vcRef: ViewContainerRef) {
        let cmpClass = class DynamicComponent {};

        let decoratedCmp = Component(metadata)(cmpClass);
        this.resolver.resolveComponent(decoratedCmp).then(factory => {
        let injector = ReflectiveInjector.fromResolvedProviders(providers, vcRef.parentInjector);
            vcRef.createComponent(factory, 0, injector, []);
        });
    }
}

I wish to edit this service so that it not only creates components on-the-fly, but can also inject services into that component. How may I do this?

Look in this line of code and please explain what providers parameter is...

let injector = ReflectiveInjector.fromResolvedProviders(providers, vcRef.parentInjector);

I can't tell what it is or where it comes from. In this case I would tell you...

"Cannot resolve all parameters"

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