Why use `deps` property in DI

2019-06-08 12:03发布

问题:

Here is the code snippet from angular.io:

{ provide: RUNNERS_UP,    useFactory:  runnersUpFactory(2), deps: [Hero, HeroService] }

...

export function runnersUpFactory(take: number) {
  return (winner: Hero, heroService: HeroService): string => {
    /* ... */
  };
};

My question is why deps property is used here? What are the general cases for using deps?

回答1:

This is a way to tell Angular dependency injections what dependencies it needs to inject to the factory function returned by runnersUpFactory.

For services there is the @Injectable() class to tell DI that it needs to analyze the constructor parameter of this class (same for @Component(), @Directive(), and @Pipe()), but this seems not to work for functions. Therefore they introduced the deps parameter.

DI will look up a provider using the key Hero and another one using HeroService and then will pass them as parameters to the factory function in the same order.

https://angular.io/docs/ts/latest/api/core/index/FactoryProvider-interface.html

deps : any[] A list of tokens which need to be resolved by the injector. The list of values is than used as arguments to the useFactory function.