gpt4 book ai didi

angular - 工厂提供者可以有可选的依赖吗?

转载 作者:太空狗 更新时间:2023-10-29 17:22:11 25 4
gpt4 key购买 nike

例如:

@NgModule ({
providers: [
{ provide: MyService,
useFactory: (optionalDep) => new MyService(optionalDep)
deps: [SOME_DEP]
}
})
class MyModule {}

useFactory 可以有可选的依赖吗?

最佳答案

根据官方文档,您可以执行以下操作:

const Location = new InjectionToken('location');
const Hash = new InjectionToken('hash');

const injector = Injector.create([{
provide: Hash,
useFactory: (location: string) => `Hash for: ${location}`,
// use a nested array to define metadata for dependencies.
deps: [[new Optional(), Location]]
}]);

expect(injector.get(Hash)).toEqual('Hash for: null');

参见 https://angular.io/api/core/FactoryProvider#example更多

关于angular - 工厂提供者可以有可选的依赖吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39278930/

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