Search code examples
angularjsangularangularjs-scope

Using Injector Class in place of ReflectiveInjector class


I am trying to dynamic load data in angular. In my approach i had used below code to load data -

 const inputProviders = Object.keys(data.inputs).map(inputName => {
  return { provide: inputName, useValue: data.inputs[inputName] };
});
const resolvedInputs = ReflectiveInjector.resolve(inputProviders);

const injector = ReflectiveInjector.fromResolvedProviders(
  resolvedInputs,
  this.cardComponent.parentInjector
);

const componentType = this.content.resolve(data.component);
const factory = this.resolver.resolveComponentFactory(componentType);

const component = factory.create(injector);

this.cardComponent.insert(component.hostView);

Lint has pointed that ReflectiveInjector will be depreciated. How should i use Injector so that my current code should work properly. I tried approach mentioned in below pages but it didn't tell about the resolve() and fromResolvedProviders() methods.

Link 1 Link 2


Solution

  • I found answer of it. Below is the code that I have used -

     const inputProviders = Object.keys(data.inputs).map(inputName => {
      return { provide: inputName, useValue: data.inputs[inputName] };
    });
    
    const injector = Injector.create(
     { providers: inputProviders,
      parent : this.cardComponent.parentInjector
    });
    
    const componentType = this.content.resolve(data.component);
    const factory = this.resolver.resolveComponentFactory(componentType);
    
    const component = factory.create(injector);
    
    this.cardComponent.insert(component.hostView);
    

    One can read more here 1 2