gpt4 book ai didi

javascript - `deps:[]` 也可以与 `useClass` 一起使用吗?

转载 作者:可可西里 更新时间:2023-11-01 02:53:04 25 4
gpt4 key购买 nike

我已经知道什么/如何使用deps
这是工厂方法需要注入(inject) token 的时候,所以我们需要像这样提供它们:

const randomFactory = (car,engine) => { return ... };
...
providers: [Car,Engine,
{ provide: 'Random',
useFactory: randomFactory ,
deps: [Car, Engine],
},
]

但我读过here :

so it's basically deps only relevant when useFactory is used, correct?
->Exactly - only for useFactory

但后来我问了in other place :

Can deps be used with useClass ? I thought they are only for useFactory –
-> Yes they can. It would be useful when you’re injecting generic dependencies that require explicitly named tokens

我不想在两个地方继续发表评论,因此我的问题是:

问题:

在什么情况下我会使用 useClassdeps

此外,即使我使用了它,请说类 Foo:

Class Foo
{
constructor ( private s1:Service1 , private s2:service2){}
}

^ 哪个已经(!)拥有了自己的构造函数。 deps依赖项会被注入(inject)到哪里? (附加到 ctor??)

场景 + 代码示例将不胜感激。

最佳答案

提供者有两种:

StaticProviderProvider

enter image description here

静态提供者

这是一种用于以静态方式(无反射)配置注入(inject)器的提供程序。

根据commit

platformXXXX() no longer accepts providers which depend on reflection.Specifically the method signature went from Provider[] toStaticProvider[].

Changelog

这是什么意思?

  1. 当我们将提供程序传递给平台时,我们必须指定 deps,因为我们必须使用 StaticClassProviderConstructorProvider 而不仅仅是 ClassProvider(见上图)。

    platformBrowserDynamic().bootstrapModule(AppModule,{ vendor :[{提供:ElementSchemaRegistry,使用类:CustomDomElementSchemaRegistry,deps: [] <===================== 这里需要}]});

  2. 当我们动态创建 Injector 时,我们必须指定 deps 因为 Injector.create takes StaticProvider 数组。

例如:

export const MyParams = new InjectionToken<string[]>('params');

export class MyService {
constructor(@Inject(MyParams) public someParameters: string[]) {}
}

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'Angular ' + VERSION.full;

constructor() {
const inj = Injector.create([
{ provide: MyService, useClass: MyService } <=== we will get an error because we have to define deps
])
}
}

https://ng-run.com/edit/5Xm4jwAoXXyAIspwF571

vendor

这是我们通常在@NgModule@Component/@Directive 元数据中编写提供程序时使用的一种提供程序

查看此答案:how the parameters of a forRoot() module's method is passed to a provider?我会说那里不需要 deps。我们只需要在 providers 数组中提供 Params,angular 就会为我们完成所有工作。


@estus 说:

deps are available only in useFactory providers but not in useClassproviders.

因为他指的是Provider(更准确地说是ClassProvider)而不是StaticProvider


附言您还可以阅读我关于StaticInjector 的文章:)

关于javascript - `deps:[]` 也可以与 `useClass` 一起使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48594944/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com