Why use `deps` property in DI

依然范特西╮ 提交于 2019-12-10 11:37:18

问题


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.



来源:https://stackoverflow.com/questions/41821883/why-use-deps-property-in-di

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!