Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 inject service into dynamic component

Tags:

angular

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?

like image 654
yazeedb Avatar asked Nov 09 '22 10:11

yazeedb


1 Answers

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"

like image 194
SoEzPz Avatar answered Nov 15 '22 07:11

SoEzPz