角度依赖注入到导出函数中 [英] Angular dependency injection into an export function
问题描述
我正在使用apollo graphql,它具有一个内部带有功能的模块.
I am using apollo graphql, and it has a module with a function inside of it.
export function createApollo(httpLink: HttpLink, connectToDevTools: true){
在此函数中,您可以定义graphql端点的网址 const uri = http://127.0.0.1/graphql
.
Inside this function you define the url for the graphql endpoint const uri = http://127.0.0.1/graphql
for instance.
我想将此URL从服务导入(这样,我只需要在一个地方更改后端服务器URL),但由于属性仍未定义,因此我无法注入该服务.
I would like to import this url form a service (so that I only have to change the backend server url in one place), but I can not inject the service, for the property stays undefined.
export function createApollo(httpLink: HttpLink, connectToDevTools: true, urlservice: UrlsService) {
const uri = urlservice.graphqlAddress;
错误:无法读取未定义的属性'graphqlAddress'
我也尝试过将服务注入模块构造函数中,但这甚至在链的下游,具有相同的结果.
I have also tried injecting the service into the modules constructor, but this is even lower down the chain, with the same results.
如何将外部属性添加到函数 createApollo
中?
How do I get an outside property into the function createApollo
?
我的服务基本上是这样的:
My service basically looks like this:
export class UrlsService {
...
graphqlAddress = 'http://192.168.2.24:8000/graphql/';
...
}
GraphQLModule提供程序:
GraphQLModule providers:
@NgModule({
exports: [ApolloModule, HttpLinkModule],
providers: [
UrlsService,
{
provide: APOLLO_OPTIONS,
useFactory: createApollo,
deps: [HttpLink],
},
],
})
export class GraphQLModule {
}
推荐答案
在声明带有参数的工厂函数时,需要在提供程序配置的依赖项设置 deps
中声明这些参数.(这在角度文档中进行了说明).因此,在您的示例中,您需要添加 UrlsService
When declaring a factory function that takes parameters, you need to declare these parameters in the dependency setting deps
, in the providers config. (This is explained in the angular doc). So in your example, you need to add UrlsService
@NgModule({
exports: [ApolloModule, HttpLinkModule],
providers: [
UrlsService,
{
provide: APOLLO_OPTIONS,
useFactory: createApollo,
deps: [HttpLink, UrlsService],
},
],
})
export class GraphQLModule {
}
此外, connectDevTools
参数看起来好像没有正确声明
Also, the connectDevTools
argument does not look like it's declared properly
export function createApollo(httpLink: HttpLink, connectToDevTools: true, urlservice: UrlsService)
这篇关于角度依赖注入到导出函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!