Search code examples
angularangular2-injectionangular2-inputs

Angular 2 DI: pass input binding to deps of factory provider


Is there an easy way to inject an input binding into the deps array of a provider factory? Below obviously does not work.

const myServiceFactory = (object: any) => {
   //...
};

@Component({
    // ...
    inputs: ['object'],
    providers: [
        {
            provide: Object,
            useValue: object,
        },
        {
            provide: MyService,
            useFactory: myServiceFactory,
            deps: [Object]
        }
    ]
})

Solution

  • As a possible solution you can try to do it something like this:

    const myServiceFactory = (self: Child) => {
      return new MyService(self.param);
    };
    
    class MyService {
      constructor(private param: string) {}
    }
    @Component({
      selector: 'child',
      template: `{{ param }}`,
      providers: [
        {
          provide: MyService,
          useFactory: myServiceFactory,
          deps: [Child]
        }
      ]
    })
    export class Child {
      @Input() param: any;
    
      constructor(private inj: Injector) { }
    
      ngOnInit() { // or ngOnChanges
        let service = this.inj.get(MyService);
      }
    }
    

    Plunker Example