Search code examples
javascriptangulartypescriptangular2-services

Injecting and resolving angular2 providers by string


I am trying to inject providers based on run time data to my angular2 component.

So far I have this:

  let type: PropertyDescriptor = Object.getOwnPropertyDescriptor(providers, provider.name);
  if (!type) return;

  let injector: Injector = ReflectiveInjector.resolveAndCreate([(<any>type).get()]);
  let resolvedProvider: IAnalyticRepository = injector.get((<any>type).get());

This attemps to create the provider but because of its child dependencies it throws an error.

The error I receive is:

Error: No provider for HttpHandler! (GoogleRepository -> HttpHandler)

How would I go on about injecting the child providers to the resolved provider as well?


Solution

  • I guess what you want is to build an injector that also includes Angular2 providers when resolving

    constructor(private injector:Injector) {}
    
    ...
    
    someMethod() {    
      let resolvedProviders = ReflectiveInjector.resolve([Car, Engine]);
      let child = ReflectiveInjector.fromResolvedProviders(
          resolvedProviders, 
          this.injector
      );
    }
    

    See also Inject service with ReflectiveInjector without specifying all classes in the dependency tree