gpt4 book ai didi

http - Angular 2 : Can't inject service in providers with useFactory

转载 作者:可可西里 更新时间:2023-11-01 16:28:00 27 4
gpt4 key购买 nike

我实现了 http 拦截器服务,它可以工作,但我的问题是我不知道如何在提供声明中注入(inject)我自己的服务。

我在控制台中收到运行时错误:No provider for MyService

HttpService拦截器类:

// all the imports...

@Injectable()
export class HttpService extends Http {
constructor(backend: ConnectionBackend,
defaultOptions: RequestOptions,
private router: Router,
private injector: ReflectiveInjector,
private myService: MyService){
super(backend, defaultOptions);
}

// methods...

在我的 app.module.ts 中,我有一组提供者:

[ 
{
provide: 'MyService',
useClass: MyService
},
{
provide: 'Http',
useFactory: (xhrBackend: XHRBackend,
requestOptions: RequestOptions,
router: Router,
injector: ReflectiveInjector,
myService: MyService) =>
new HttpService(xhrBackend, requestOptions, router, injector, myService),
deps: [XHRBackend, RequestOptions, Router, Injector, MyService]
}]

我检查了几个 SO 问题/答案,但找不到类似的例子..

谢谢!

最佳答案

deps 仅说明工厂需要哪些依赖项(以便它们可以正确注入(inject))。但它实际上并不提供依赖性。您仍然需要将它添加到 providers 数组

providers: [
MyService,
{
provide: 'Http',
...
}
]

关于http - Angular 2 : Can't inject service in providers with useFactory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40408309/

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